/**
 *  Zing News Code
 *  Version 3.52 (19/07/2014)
 */

// check if it's correct domain
var isEmbed = (window !== window.parent), Player;

if ((typeof debug_mode === "undefined") && (window.location.hostname.indexOf('localhost') < 0) && (window.location.hash.search(/embed|singleplayer|redirected/ig)<0) && (isEmbed || window.top.location.hostname.indexOf('news.zing.vn') < 0)) {
    var origin = window.location.pathname;
    if (DEVICE.type === 'desktop') {
        window.top.location.href = 'http://news.zing.vn/' + origin + '#redirected';
    }
}

if(typeof debug_mode == 'undefined') {
    var debug_mode = (window.location.hash.search('debug')>=0);
}

$.ajaxSetup({
    timeout: 5000
});

// initial configuration
var APP_ID = '622829237762080', fullbackground = false;
var INITIAL_TIME = now();
var page = new Page();
if (!$.support.transition) $.fn.transition = $.fn.animate;

$(document).ready(function () {
    if ($.cookie) {
        $.cookie.json = true;
    }

    if ($(document).width() > 1200) {
        DEVICE.screen = "wide";
    } else {
        DEVICE.screen = "standard";
    }    

    page.init();

    // check if version cookie set, if yes, extend it for another day
    var cookieMobile = $.cookie('znews_mobile');
    if (cookieMobile != null) {
        $.cookie('znews_mobile', cookieMobile, {
            expires: 1,
            path: '/'
        });
    }

    if(page.getPageType()=='home') {
        /*
        if ($('#banner_chuyentrang').length==0) {
            $('#xa-hoi').before('<div id="banner_chuyentrang" style="margin-top:0 !important;"><a href="http://news.zing.vn/special/bien-dong.html" target="_blank" title="Chuyên trang: Trung Quốc đặt giàn khoan trên vùng biển Việt Nam"><img src="http://stc.v3.news.zing.vn/images/banner_biendong_small.jpg" style="width:100%; height:auto"></a></div>');    
        }
        */
        // world cup quick fix
        if($(document).width()>=600) {            
            var $wc_cover = $('#world-cup article.featured .cover');
            if ($wc_cover.length>0) {
                $wc_cover.attr('style',$wc_cover.attr('style').replace('w210','w480'));
            }
            $('section#world-cup.category > header').append('<a href="http://news.zing.vn/World-Cup-2014.html" target="_blank" class="wc"></a>');    
            
        }        
    }

    // quick fix for banner tuyen dung
    $('img[src*="banner_tuyendung.jpg"]').attr({'src':'http://stc.v3.news.zing.vn/images/bannertuyendung.jpg','width':'300','height':'90'});
    
    if(page.getPageType()=='article' && page.article.getArticleType()=='text') {
        $('.metabox').before('<div id="abd_vidinpage" style=""><div id="pva"></div></div><script type="text/javascript">var abd_width = 480;var abd_height = 300; var abd_config="http://delivery.adnetwork.vn/247/ovavideoad/zid_1403085181/wid_1287112339/eff_vidinpage/";</script>');
        var script = document.createElement( 'script' );
        script.type = 'text/javascript';
        script.src = 'http://media.adnetwork.vn/video-inpage/abd.vid_inpage.js';
        $('body').append(script);
    }
    

});

$(window).bind('load', function () {
    page.setupScrollbar('.scroll');
    page.slider.init();
    page.ticker.init();

    /* Setup advertising slots */
    if(DEVICE.type=='desktop') {
        loadPlugin('scrollfixed', 'jquery.scrolltofixed.js', function(){
            //log('scroll to fixed loaded');
            var $aside = $('section.article_content > aside, section.cate_sidebar');
            $aside.css('height',($('section.article_content > article').height())+'px');
            if((page.getPageType()!='category' && page.getPageType()!='article') || (page.getPageType()=='article' && page.article.getArticleType()!='text') || ($aside.height()-$aside.find('.related').height()-$aside.find('.topview').height()-20) < 600) {
                $('#advSkyscraper1').hide();
                //log('Not enough space');
                log('Hide skycraper banner');
            } else {
                log('Show skycraper banner');
                $('#advSkyscraper1').show();
                AdtimaZingNews.Helpers.reloadBanner(AdtimaZingNews.position.sc1);
                $('#advSkyscraper1').scrollToFixed({
                    marginTop: 45,
                    limit: function() {
                        var limit = $('.article_content > article').outerHeight()-250;
                        return limit;
                    },
                    zindex:99999,
                    preAbsolute:function(){
                        $(this).addClass('noscroll');
                    },
                    postAbsolute :function(){                
                        $(this).removeClass('noscroll');
                    }
                });
            }        

            if(page.getPageType()=='article' || page.getPageType()=='category') {
                var $sb = $('.wrapper > .sidebar, #category > .sidebar');
                $sb.css({'height':($sb.parents('.wrapper').height()-300)+'px'});
                log('Show Big banner');
                var b_offset = 0;
                if ($sb.find('#promotedposts').length>0) {
                    b_offset = $sb.find('#promotedposts').offset().top + $sb.find('#promotedposts').height();
                }
                if(($sb.height()-b_offset)>600) {
                    $sb.append('<div id="advR3" class="banner" style="width: 300px; height: 600px; margin-bottom: 10px;"></div>');
                    AdtimaZingNews.Helpers.reloadBanner(AdtimaZingNews.position.r3);
                    $('#advR3').scrollToFixed({
                        marginTop: 45,                
                        zindex:99999,
                        limit: function() {
                            var limit = $(document).height()-1000;
                            return limit
                        },
                        offset:false,
                        preAbsolute:function(){
                            $(this).addClass('noscroll');
                        },
                        postAbsolute :function(){                
                            $(this).removeClass('noscroll');
                        }
                    });    
                }                        
            } else {
                log('Hide big banner');
            }

            $('#top .categories').scrollToFixed({
                marginTop: 0,                
                zindex:99999,                
                offset:false,
                preAbsolute:function(){
                    $(this).addClass('noscroll');
                },
                postAbsolute :function(){                
                    $(this).removeClass('noscroll');
                },
                fixed: function(){
                    var $head = $(this);
                    $head.addClass('fixedtop');
                },
                unfixed: function(){
                    var $head = $(this);
                    $head.removeClass('fixedtop');
                }
            });    

        });    
    }

    if (page.getPageType()=='article') {
        var tracker = page.storage.load('history');
        if(tracker==null || tracker===false) {tracker = "";}
        if (tracker.search(page.article.getArticleId())<0) {
            tracker += page.article.getArticleId()+',';
            page.storage.insert('history',tracker);
        }
        $('.wrapper > .sidebar').css('z-index',-1);
    }

    // setup gif image
    page.setupGifCover();


    if (window.location.hash.search('app')<0 && page.getPageType()!='article') {
        if(DEVICE.platform=='ios') {
            announce(
                'app_announce',
                'CẬP NHẬT: App Zing.vn trên iPhone/iPad đã được cập nhật phiên bản mới ổn định hơn và hỗ trợ bài video. Tải và trải nghiệm ngay!',
                'https://itunes.apple.com/vn/app/zing.vn/id818187465?mt=8',
                {
                    platform:'ios'
                }
            );
        }
        else if (DEVICE.platform == 'android') {
            announce(
                'app_announce',
                'THÔNG BÁO: Zing.vn ra mắt phiên bản app Zing 2.0 dành cho thiết bị Android đẹp và tiện lợi hơn. TẢI NGAY!',
                'market://details?id=com.zing.znews',
                {
                    platform:'android'
                }
            );
        }
    }

}).on('blur', function () {
    INITIAL_TIME = now();
});

/**
 * Check if user comeback after certain amount of time then reload the content
 */
if (page.getPageType() == 'home') {
    $(window).on('focus', function () {
        var time = Math.floor(( now() - INITIAL_TIME) / 60000);
        //ga('send', 'event', 'Window', 'Refocus Interval',window.location.pathname, time);
        if (time >= 15) {
            //ga('send', 'event', 'Window', 'Auto Reloading', window.location.pathname, time);
            window.location.reload(true);
        }
    });
}

/* All functions related to page*/
function Page() {
    var self = this;
    var cachedPageType;


    this.livestream = new LiveStream();
    //this.interview = new Interview();
    this.ticker = null;
    this.slider = new Slideshow('section.pictures', 'article');
    this.article = new Article();
    this.socialplugin = new SocialPlugin();
    this.storage = new Storage('local');
    this.navigationMenu;

    this.init = function () {        

        if(self.getPageType()=='focus') {
            self.setupTopicPage();    
        }
        
        Player = new VideoPlayer().init();
        self.setupTrackingLink();
        self.ticker = new NewsTicker($('.hotnews'), 'li');
        self.renderSocialCount();

        self.setupSearchBox();
        self.article.init();

        //self.showLiveAlert();

        if(!fullbackground) { 
            self.navigationMenu = new NavigationMenu();
            self.navigationMenu.show();
        }

        self.setupToolbox();
        self.socialplugin.init();

        $('#top .parent').hover(function () {
            $(this).addClass('active');
        }, function () {
            $(this).removeClass('active');
        });

        // render article publish time
        var $timers = $('time');
        for (var i = 0, length = $timers.length; i < length; i++) {
            var $timer = $timers.eq(i),
                friendly = $timer.html() + page.formatTime($timer.attr('datetime'), {
                    friendly: $timer.hasClass('friendly')
                });

            $timer.html(friendly);
        };        

        // initialize grid layout
        var $gridView = $('.gridview');
        if ($gridView.length > 0 && DEVICE.type == "desktop" && $gridView.find('article').length>0) {
            loadPlugin('isotope', 'isotope.1.5.25.js', function(){
                $gridView.isotope({
                    // options
                    itemSelector: 'article',
                    layoutMode: 'masonry',
                    transformsEnabled: false,
                    gutterWidth: 20
                });
            });

        }

        // setup category feed subscription dropdown box on homepage
        $('section.category .followbox').hover(
            function () {
                $(this).addClass('hovering');
            },
            function () {
                $(this).removeClass('hovering');
            }
        );

        // initialize live stream
        if ($('#livestream').length > 0 && $('#livestream .controller').length > 0) {
            page.livestream.init($('#livestream .controller').attr('data'));
            $('#livestream').addClass('live');
        }

        // initialize live interview if status = live/question
        var $interviews = $('div[submit*="interview"]');
        $interviews.each(function(){
            (new Interview()).init(this,$(this).attr('data'),$(this).attr('submit'));
        });    

        // showing pr articles in category page
        var pageType = self.getPageType();
        if (pageType === 'category') {
            var target = '.cate_content section.cate_content';
            if ($(target).length==0) {
                target = 'section.cate_content';
            }
            var $adsArticles = $(target+' article.advertising');
            if ($adsArticles.length > 0) {
                $articles = $(target+' article:not(.advertising)');

                var adsIndex = 0,
                    adsLength = $adsArticles.length;

                for (var i = 0, length = $articles.length; i < length; i += 2) {
                    if (adsIndex >= adsLength) {
                        break;
                    }
                    $adsArticles.eq(adsIndex).insertAfter($articles.eq(i)).show();
                    ++adsIndex;
                }

                while (adsIndex < adsLength) {
                    $adsArticles.eq(adsIndex).insertAfter($(target+' article:last-of-type')).show();
                    ++adsIndex;
                }
            }
        }

        /* Banner ad */
        if (self.getPageType() == 'home') {                        
            //$('.sidebar>section.pictures').before('<a href="http://news.zing.vn/Chieu-75-phong-van-truc-tuyen-Minh-Thuy--Nhat-Thuy-post414114.html#banner" target="_blank" style="display:block; margin-bottom:10px;"><img src="http://stc.v3.news.zing.vn/images/minhthuynhatthuy300.jpg" /></a>');
        }


        return self;
    };    

    this.showLiveAlert = function(){        
        if (self.getPageType()!='home' && $('#livestream').length==0 && $('#video.singleplayer').length==0) {
            log('Live Alert');            
            var $breakingnews = $('<div>',{'id':'breakingnews'}).html('<label style="">Trực tiếp</label>');
            self.article.fetchArticle('http://news.zing.vn/api/mobile/live.json', function(articles) {                
                var now = new Date().getTime(), oneday = 24*60*60*1000, hasArticle = 0;
                for(var i=0;i<articles.length;i++) {
                    var article = articles[i];
                    var age = Math.round(Math.abs((now - parseInt(article.time)*1000)/oneday));
                    if (age<=1) {
                        $breakingnews.append('<a target="_blank" href="'+article.link+'#laban_home">'+article.title+'</a>');
                        hasArticle++;
                        if(hasArticle==2) {
                            break;
                        }                        
                    }
                }
                if(hasArticle>0) {
                    log('Show breaking news');                    
                    $('#zingheader').after($('<div>',{'class':'wrapper alertbar'}).append($breakingnews));
                } else {
                    log('No breaking news to show');
                }
            },15);
        }
    }

    this.hideSidebar = function(){
        fullbackground = true;
        $('#navigation_toolbox').remove();
        $('#pushnotification').remove();
    }

    // insert tracking code for links
    this.setupTrackingLink = function () {
        var $articles = $('article');
        for (var i = 0, length = $articles.length; i < length; i++) {
            var $article = $articles.eq(i);
            var target = generateLinkTrack($article);
            $article.find('> .cover a, > header h1 a').attr('href', target);
        };

        var $relates = $('article ul.relate a');
        for (var i = 0, length = $relates.length; i < length; i++) {
            var $relate = $relates.eq(i);
            $relate.attr('href', $relate.attr('href') + '#relate-article');
        };

        var $inners = $('.inner-article a');
        for (var i = 0, length = $inners.length; i < length; i++) {
            var $inner = $inners.eq(i);
            $inner.attr('href',$inner.attr('href')+'#inner-article');
        };
    };

    // render social counter for articles
    this.renderSocialCount = function () {
        var news = "",
            $hotArticle;
        var $socialCounters = $('.social.hot', 'article');

        for (var i = 0, j = $socialCounters.length; i < j; i++) {
            var $socialCounter = $socialCounters.eq(i);

            $socialCounter.show().on("mouseenter", function (e) {
                self.showHoverBox('<div class="content">Bài viết có nhiều phản hồi của bạn đọc</div>', {
                    'top': e.clientY + 15,
                    'left': e.clientX
                });
            }).on('mouseleave', function () {
                $('#popup').hide();
            });
            try {
                $hotArticle = $socialCounter.parents('article');
                var atitle = $hotArticle.find('> header h1 a').text();
                var aCover = $hotArticle.find('> .cover');
                var aTime = new Date($hotArticle.find('time').attr('datetime'));


                if ($(aCover).find('img').length > 0) {
                    aCover = $(aCover).find('img').attr('src');
                } else {
                    aCover = $(aCover).css('background-image').replace(/url\(|\)/gi, '');
                }
                if (news.search(atitle) < 0 && Math.floor((INITIAL_TIME - aTime.getTime()) / 86400000) == 0) {
                    news += '<li><a href="' + $hotArticle.find('> header h1 a').attr('href') + '"><span class="cover" style="background-image:url(' + aCover + ')"></span>' + atitle + '</a></li>';
                }
            } catch (e) {};
        };

        if ($socialCounters.length > 0) {
            $('body').append($('<div>', {
                'id': 'hotnews'
            }).html('<ul>' + news + '</ul'));

            var $hotnews = $('#hotnews');

            $('#zingheader .wrapper').append('<div id="noti5"><a href="#" class="btnHot">NÓNG 24h</a></div>');
            $('#noti5 .btnHot').append('<span>' + $hotnews.find('li').length + '</span>').on('click', function () {
                if ($hotnews.is(':visible')) {
                    $hotnews.hide();
                    $('body').unbind('click');
                } else {
                    $hotnews.show();
                    setTimeout(function () {
                        $('body').on('click', function () {
                            $hotnews.hide();
                        });
                    }, 200);
                }
                return false;
            });
        }
    };

    // Display and hiding tooltip
    this.showHoverBox = function (content, position, styles, action) {
        var $popup = $('#popup');

        if ($popup.length == 0) {
            $('body').append($('<div>', {
                id: 'popup'
            }));

            $popup = $('#popup');
        }

        $popup.html(content);
        if (position) {
            $popup.css({
                top: position.top + 'px',
                left: position.left + 'px'
            });
        }

        if (action) {
            action();
        }

        if (styles) {
            $popup.css(styles);
        }

        $popup.show();
    };
    this.hideHoverBox = function () {
        var $popup = $('#popup');
        $popup.empty().hide();
        $popup.unbind();
    };

    // Setup Search box
    this.setupSearchBox = function () {
        var $searchBox = $('#searchbox'),
            $searchInput = $searchBox.find('input[type="text"]');

        $searchInput.focus(function () {
            if ($searchInput.val() == 'Nhập nội dung cần tìm...') {
                $searchInput.val('');
            }
        }).blur(function () {
            if ($.trim($searchInput.val()) == '') {
                $searchInput.val('Nhập nội dung cần tìm...');
            }
        });

        $searchBox.submit(function () {
            var url = window.location.origin,
                keyword = $.trim($searchInput.val());
            if (keyword != '' && keyword != 'Nhập nội dung cần tìm...') {
                keyword = keyword.replace(/\s+/, "-");
                url += "/tim-kiem/" + encodeURIComponent(keyword) + '.html';
            }
            window.location.href = url;
            return false;
        });
    };

    // Display shortcut link on the right edge
    this.setupToolbox = function () {
        $toolbox = $('#toolbox');
        $btnToTop = $toolbox.find('li.toTop a');
        $btnEmail = $toolbox.find('li.email a');
        $btnPhone = $toolbox.find('li.phone a');                

        $(window).bind('scroll', function () {
            var scrollTop = $(window).scrollTop();
            
            /*
            var $fixedboxes = $('.fixedBox');                
            for(var i=0; i<$fixedboxes.length;i++) {
                if (scrollTop > $fixedboxes.eq(i).offset().top && ! $fixedboxes.eq(i).hasClass('fixed')) {
                    $fixedboxes.eq(i).css({'width':$fixedboxes.eq(i).data('width')+'px','left':$fixedboxes.eq(i).data('left')+'px'}).addClass('fixed');
                } else {
                    $fixedboxes.eq(i).removeClass('fixed');
                }
            }
            */

            if (scrollTop > 200) {
                $btnToTop.stop().fadeIn();

                $('.btnToTop').css('display', 'block');

                if (scrollTop > 400 && page.article.getArticleType() != null && !$('#pushnotification').hasClass('hidden') && !$('#pushnotification').is(':visible')) {
                    if(!$('body').hasClass('appview')){page.showBottomBar();}
                }

                if(!fullbackground) {
                    self.navigationMenu.show();
                    self.navigationMenu.updateCurrent(scrollTop);    
                }
                
            } else {
                if(!fullbackground) {
                    self.navigationMenu.hide();
                    $btnToTop.stop().fadeOut();
                    $('#pushnotification .actions .btnToTop').hide();    
                }
                
            }
        });
        $btnToTop.on('click', function () {
            self.scrollTo();
            return false;
        });
        $btnEmail.on('click', function () {
            showEmailBox();
            return false;
        });
        $btnPhone.on('click', function () {
            showPhoneBox();
            return false;
        });
    };

    // setting up scroll for overflow content (without scrollbar)
    this.setupScrollbar = function (scrollElement) {
        var $scrollElement = $(scrollElement);
        if ($scrollElement.length > 0 && DEVICE.type == "desktop") {
            $scrollElement.mCustomScrollbar({
                scrollButtons: {
                    enable: false
                },
                theme: "dark",
                autoHideScrollbar: true,
                autoDraggerLength: false
            });
        }
    };

    // utilities to format time string
    this.formatTime = function (timestring, options) {
        //console.log(timestring);
        var difference, days, hours, minutes, month, prefix, date;

        if (parseInt(timestring)<10000) {
            date = new Date(timestring.replace(/-/g,'/').replace('+', ' +'));
        } else {
            date = new Date((parseInt(timestring)-25200)*1000);
        }

        prefix = options == null || options.prefix == null ? "" : options.prefix;

        if (options && options.friendly === true) {
            difference = now() - date.getTime();

            days = Math.floor(difference / 1000 / 60 / 60 / 24);
            difference -= days * 1000 * 60 * 60 * 24;
            hours = Math.floor(difference / 1000 / 60 / 60);
            difference -= hours * 1000 * 60 * 60;
            minutes = Math.floor(difference / 1000 / 60);
            difference -= minutes * 1000 * 60;

            //console.log('friendly:'+timestring);
            if (days == 0 && hours == 0) {
                return prefix + minutes + " phút trước";
            } else if (days == 1) {
                return prefix + "Hôm qua, lúc " + date.getHours() + " giờ " + date.getMinutes() + ' phút';
            }
        }

        hours = (date.getHours() < 10 ? '0' : '') + date.getHours();
        minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
        days = (date.getDate() < 10 ? '0' : '') + date.getDate();
        month = (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1);

        return prefix + " " + hours + ":" + minutes + " ngày " + days + "/" + month + "/" + date.getFullYear();
    };

    // bookmarking
    this.addBookmark = function () {
        if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark
            window.sidebar.addPanel(document.title, window.location.href, '');
        } else if (window.external && ('AddFavorite' in window.external)) { // IE Favorite
            window.external.AddFavorite(location.href, document.title);
        } else if (window.opera && window.print) { // Opera Hotlist
            this.title = document.title;
            return true;
        } else { // webkit - safari/chrome
            if (DEVICE.browser=='chrome') {
                window.location.href="https://chrome.google.com/webstore/detail/zing-plus/jagbegdddghlidpmkamknochllodpdco?hl=vi";
            } else {
                alert('Vui lòng bấm tổ hợp phím ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D để lưu trang.');
            }

        }
    };

    // Display and hide dialog
    this.showDialog = function (title, content, actions) {
        if (content == null) {
            return;
        }

        var $dialog = $('#dialog');

        if ($dialog.length == 0) {
            $('body').append($('<div>', {
                id: 'dialog'
            }));

            $dialog = $('#dialog');

            var dialogHtml = '<div>' +
                '<div class="header"></div>' +
                '<div class="content"></div>' +
                '<div class="action"><button class="btnSubmit">Đồng ý</button><button class="btnCancel">Đóng</button></div>' +
                '</div>';

            $dialog.html(dialogHtml);
        }

        var $btnSubmit = $dialog.find('.action button.btnSubmit'),
            $btnCancel = $dialog.find('.action button.btnCancel');

        $dialog.find('.header').html(title || 'Thông báo');
        $dialog.find('.content').html(content);

        $btnCancel.text('Đóng');

        if (actions != null) {
            if (actions.submit != null) {
                $btnSubmit.html(actions.submit.text || 'Đồng ý');

                $btnSubmit.on('click', function () {
                    actions.submit.action();
                }).show();
            } else {
                $btnSubmit.hide();
            }
            if (actions.cancel != null) {
                if (actions.cancel.text != null) {
                    $btnCancel.html(actions.cancel.text);
                }
            }
        }

        $btnCancel.on('click', function () {
            if (actions && actions.cancel && actions.cancel.action) {
                actions.cancel.action();
            }
            self.closeDialog();
        });

        $btnCancel.show();

        $dialog.find('> div').css({
            'margin-top': '-' + Math.round($('#dialog > div').height()+100) + 'px'
        });

        $dialog.show();
    };
    this.closeDialog = function () {
        //console.log("close dialog");
        var $dialog = $('#dialog');
        $dialog.hide();
        $dialog.find('.header').empty();
        $dialog.find('.content').empty();
        $dialog.find('.action button').unbind('click').hide();
    };

    // display notification bar at the bottom
    this.showBottomBar = function () {
        if (DEVICE.screen != 'wide') {
            $('#pushnotification').css('bottom', '-50px');
            $('#pushnotification').show().transition({
                'bottom': '0px'
            });
        }
    };
    this.hideBottomBar = function () {
        if (DEVICE.screen == 'wide') {
            $('#pushnotification').hide();
        } else {
            $('#pushnotification').transition({
                'bottom': '-70px'
            }, 500, function () {
                $('#pushnotification').hide();
                $('#pushnotification').addClass('hidden');
            });

        }

    };

    // show navigation
    this.pushNotification = function (content, action) {
        if ($('#popNotification').length == 0) {
            $('body').append($('<div>', {
                'id': 'popNotification'
            }).html('<div>'));
        }
        if (content == null) return;
        $('#popNotification > div').html(content);
        if (action) {
            $('#popNotification > div').bind('click', function () {
                action();
            });
        } else {
            $('#popNotification > div').bind('click', function () {
                self.hidePopNotification();
            });
        }
        $('#popNotification').fadeIn(500);
        /*
        $('#popNotification').show().transition({
            'right':'10px'
        });
        */
    };
    this.hidePushNotification = function () {        
        $('#popNotification').fadeOut(400, function () {
            $('#popNotification > div').unbind().empty();
        });
    };

    // show fanpage following dialog
    this.showFollowDialog = function () {
        page.storage.insertContent('popup_follow','1');
        self.showDialog(
            'Trở thành fan của Zing.vn',
            '<p>Bạn thường xuyên đọc Zing.vn? Bạn muốn nhận tin tức mới nhất từ Zing.vn? Hãy nhấn nút "Thích" bên dưới để trở thành nhận thông tin từ chúng tôi trên Facebook.</p>' +
            '<div>' +
                '<iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fzing.vn&amp;width&amp;height=258&amp;colorscheme=light&amp;show_faces=true&amp;header=false&amp;stream=false&amp;show_border=true&amp;appId=622829237762080" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:258px; width:100%; margin-top:10px;" allowTransparency="true"></iframe>' +
            '</div>'
        );        
    };

    // detect copy content mechanism
    this.getSelection = function () {
        if (window.getSelection) {
            return window.getSelection();
        } else if (document.getSelection) {
            return document.getSelection();
        }
        return false;
    };
    this.insertCopy = function () {
        var body_element = document.getElementsByTagName('body')[0];
        var selection = self.getSelection();
        if (selection === false) return;
        if (selection.toString().length < 500) return;        
        var pagelink = "<br /><br /> Bài viết: <a href='" + document.location.href + "' target='_blank'>" + document.location.href + "</a><br /><br /><a href='http://news.zing.vn' title='Zing News' target='_blank' style='display:block;font-size:0;line-height:0;'>Nguồn Zing News</a><br />";
        // change this if you want
        var copytext = selection + pagelink;
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        body_element.appendChild(newdiv);
        newdiv.innerHTML = copytext;
        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {
            body_element.removeChild(newdiv);
        }, 0);
    };

    // Fullscreen feature
    this.launchFullScreen = function (element) {
        //ga('send', 'event', 'Slideshow', 'Switch fullscreen', window.location.pathname);
        if (element.requestFullScreen) {
            element.requestFullScreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen();
        }
    };
    this.cancelFullscreen = function () {
        if (document.cancelFullScreen) {
            document.cancelFullScreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }
    };
    this.isFullScreen = function () {
        var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
        return (fullscreenElement != null);
    };
    this.isFullscreenEnable = function () {
        return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;
    };

    // Scrollto
    this.scrollTo = function (pos) {
        var dest = pos || 0;
        $("html, body").animate({
            'scrollTop': dest + 'px'
        }, Math.abs($(window).scrollTop() - dest) / 5);
    };

    // get pagetype
    this.getPageType = function () {
        if (cachedPageType) {
            return cachedPageType;
        }

        var pathname = window.location.pathname,
            pageType = '';

        if (pathname == '/' || pathname.indexOf('index.html') > 0) {
            pageType = 'home';
        } else if (/-post[0-9]+\.html/i.test(pathname)) {
            pageType = 'article';
        } else if (/\/tag\/[^\.]*\.html/i.test(pathname)) {
            pageType = 'tag';
        } else if (/\/tim-kiem\/[^\.]*\.html/i.test(pathname)) {
            pageType = 'search';
        } else if (/\/tieu-diem\/[^\.]*\.html/i.test(pathname)) {
            pageType = 'topic';
        } else if (/\/chuyen-de\//i.test('pathname')) {
            pageType = 'special';
        } else if (/\/special\//i.test('pathname')) {
            pageType = 'focus';
        } else {
            pageType = 'category';
        }

        cachedPageType = pageType;

        return pageType;
    };

    // setup chuyen trang
    this.setupTopicPage = function(){
        log('Setup topic Bien dong');
        var $topicpage = $('.themewrapper');
        if ($topicpage.length==0) return;

        var $gridView = $('.gridview');
        loadPlugin('isotop2', 'isotope.2.0.js', function(){                                         
            $gridView.isotope({
                itemSelector: 'article',                                
                masonry: {
                    gutterWidth: 20
                }
            });                        

            var $topics = $topicpage.find('a');
            if($topics.length==0) return;

            $topics.eq(0).addClass('activebd');
            self.loadTopicContent($topics.eq(0),$gridView,1);

            $topics.on('click',function(e){
                e.preventDefault();                
                if ($(this).hasClass('activebd')) return;                
                $('.themewrapper').find('.activebd').removeClass('activebd');
                $(this).addClass('activebd');

                self.loadTopicContent(this,$gridView,1);
            });
        });            
    }

    this.popupArticle = function(url, cate) {
        var $container = $('#popup_article');
        if($container.length==0) {
            $container = $('<div>',{'id':'popup_article'});
            $container.append('<div class="header"><h1>Bài viết</h1><a class="btnClose" href="#">Đóng</a></div><div class="content"></div>');
            $container.find('a.btnClose').on('click',function(e){
                e.preventDefault();
                $container.transition({
                    'width':'0px','height':'0px',
                    'margin-left':'0px',
                    'margin-top':'0px',
                    easing:'snap',
                    duration:500
                }).hide();
                $container.find('.content').html("");
                $('body').removeClass('noscroll');
            });
            $('body').append($container);
        } 
        $container.find('.header h1').html(cate);
        var height = Math.round($(window).height()*0.8);
        $container.show().transition({
            'top':'50px',
            'width':'800px',

            'height':($(window).height()-100)+'px',
            'margin-left':'-400px',
            //'margin-top':'-'+Math.round(height/2)+'px',
            easing:'snap',
            duration:500 
        });
        setTimeout(function(){
            $container.find('.content').append('<iframe src="'+url+'"></iframe>');
        },600);
        //$('body').addClass('noscroll');
    };

    this.loadTopicContent = function(menuitem, container, page){
        var $listing = $(container); 
        $listing.find('p.more').remove();
        if(page==null || page==1) {
            $listing.isotope( 'remove', $listing.find('article') ) ;
            $listing.isotope();                
        } 

        $listing.addClass('loading');
        
        var url = 'http://news.zing.vn/api/mobile/';
        if($(menuitem).hasClass('tag')) {
            url += 'tag.json?name='+$(menuitem).attr('href').replace('#','')+'&p='+page+'&c=50';
        } else {
            url += 'topic.json?eventid='+$(menuitem).attr('href').replace('#','')+'&p='+page+'&c=50';
        }
        if($(menuitem).hasClass('picture')) {
            url += '&types=2';   
        } else if ($(menuitem).hasClass('video')) {
            url += '&types=4';
        }
        self.article.fetchArticle(url,function(articles){            
            // initialize grid layout
            if(articles.length>0) {
                for (var i = 0; i < articles.length; i++) { 
                    var b = articles[i];
                    $a = self.article.renderArticleHTML(articles[i],'chuyentrang');
                    $a.find('a').attr('target','_blank');                        
                    if(DEVICE.type=='desktop') {
                        $a.on('click', function(e){
                            e.preventDefault();                            
                            var cur = $(this).attr('data-source');
                            if($(this).hasClass('video')) cur += '#singleplayer';
                            else cur += '#apptabletembed';
                            var cate = $(this).find('.cate').html();
                            self.popupArticle(cur, cate);
                        });
                    }
                    
                    $listing.append($a).isotope( 'appended', $a );
                    $listing.isotope();
                }
            }
            $listing.removeClass('loading');
            $listing.isotope();

            $listing.append('<p class="more"><a class="btnMore" href="#'+(page+1)+'" title="Xem thêm">Xem thêm</a></p>');
            $listing.find('.btnMore').on('click',function(e){
                e.preventDefault();
                self.loadTopicContent(menuitem, container, page+1);
            });

        });
    }

    // autoplay gif cover
    this.setupGifCover = function(){
        // Setup gif display mechanism
        var $gifs = $('.cover[style*="_gif.jpg"]');        
        for(var i=0;i<3 && i<$gifs.length;i++) {
            var $gif = $gifs.eq(i);                        
            var animate_cover = $gif.css('background-image').replace(/url\(|\)/g,'').replace('_gif.jpg','.gif');            
            self.renderGifCover($gif, animate_cover);            
        }             
    }
    this.renderGifCover = function(elm, gif) {
        var $gif = $(elm);
        log('Render gif cover', $gif);
        var animation = $('<img>',{'src':gif,'class':'preloading'}).css({'width':'0px', 'height':'0px'}).ensureLoad(function(){
            $gif.css({'background-image':'url('+gif+')','background-size':'cover'});
            log('Render Gif cover: '+gif);
        });
        $('body').append(animation);
    }
}

/* Auto load article function */
function InfiniteArticle() {
    var articleList = [],
        PAGEVIEW_TRACKED = [],
        STOPPED = false,
        IS_SCROLLING_TO = false,
        currentArticleIndex = -1,
        $elements,
        $contentStack,
        $discover,
        $window,
        article,
        currentState,
        scrollState;

    var scrollToArticle = function(url) {
        var articleId = getArticleId(url);
        var $article = $('section.article_content[data-id='+ articleId +']');
        if ($article.length) {
            IS_SCROLLING_TO = true;
            //var top = $article.offset().top;
            //console.log(top);
            //$(window).scrollTop(top);
            //console.log($(window).scrollTop());


            //$article[0].scrollIntoView();
            log('Scroll to article '+url);
            switchArticle($article[0], true);

        }
    };

    var switchArticle = function(elm, manual) {
        var $elm = $(elm),
            url = $elm.data('src');

        $elm.removeClass('inactive');

        // saved read article so that we don't show it again
        //var $prev = $elm.prevAll('.article_content');

        var tracker = page.storage.load('history');
        if(tracker==null || tracker===false) {tracker = "";}
        var current_article = $elm.attr('data-id');
        if (tracker.search(current_article)<0) {
            log('Save read article #'+current_article);
            tracker += current_article+',';
            page.storage.insert('history',tracker);
        }


        if (!currentState) {
            currentState = url;
        }
        scrollState = url;

        //log('Scroll State: '+scrollState);


        if (scrollState != currentState || manual) {
            var tmpUrl = url.split('#')[0];
            currentState = scrollState;
            //log('Current State: '+currentState);

            article.renderFacebookWidgets(url, true);
            if (PAGEVIEW_TRACKED.indexOf(tmpUrl) === -1) {
                PAGEVIEW_TRACKED.push(tmpUrl);

                var tmp = url.split('/'),
                    path = tmp[tmp.length - 1];

                var cate = '';

                if ( typeof cate_path != "undefined") {
                    cate = cate_path+'/';
                }

                log('Sending pageview '+path.replace(/#.*/ig,''));

                ga('send', 'pageview', {
                    'page': '/' + cate + path.replace(/#.*/ig,'')+'#inline-load',
                    'title': $elm.data('title').replace(/\s-[^-]*\s-\sZing News/gi, '')
                });


                $('body').append($('<img>', {
                    'width' : 1,
                    'height' : 1,
                    'src' : 'http://log.news.zing.vn/Counter.aspx?key=story&prm='+$(elm).attr('data-id')+'&rand=' + Math.random()
                }).css('position', 'absolute'));


                $('body').append($('<img>', {
                    'width' : 1,
                    'height' : 1,
                    'src' : 'http://log.news.zing.vn/Counter.aspx?key=all&prm=&rand=' + Math.random()
                }).css('position', 'absolute'));


            }

            if (!manual) {
                // use replaceState instead of pushState so that when user hit back, we will move back to previous page
                History.replaceState({}, $elm.data('title'), tmpUrl);
            } else {
                log('Manual',manual);
                setTimeout(function() {
                    elm.scrollIntoView();
                    //log($(elm).offset().top);
                    //page.scrollTo($(elm).offset().top);
                }, 0);
            }
        }
    };

    var onScroll = function(e) {
        if (IS_SCROLLING_TO) {
            IS_SCROLLING_TO = false;
            return;
        }

        //log(e);

        $elements.each(function(i, elm) {
            if (isElementInViewport(i, elm)) {
                showArticle(elm);
                return false;
            }
        });

        var b = $(this);
        b.data("scrollTimeout") && clearTimeout(b.data("scrollTimeout"));
        b.data("scrollTimeout", setTimeout(onScrollStop, 250, this));
    };

    var onScrollStop = function() {
        var length = $contentStack.length,
            offsetTop = Math.round($(window).height() / 2),
            articleVisible = false;

        $contentStack.addClass('inactive').each(function(i, elm) {
            var $elm = $(elm);
            if (isElementInViewport(i, elm, offsetTop)) {
                articleVisible = true;
                currentArticleIndex = i;
                switchArticle(elm);
                return false;
            }
        });

        if (!articleVisible) {
            switchArticle($contentStack.get(currentArticleIndex));
        }
    };

    var getArticleId = function(url) {
        var matches = url.match(/-post([0-9]+)\.html/i);
        return matches && matches[1] ? matches[1] : 0;
    };

    var showArticle = function(elm) {
        var $elm = $(elm),
            url = $elm.data('src'),
            articleId = $elm.data('id');

        if ($elm.hasClass('loading') || !url) {
            return;
        }

        $elm.addClass('loading');

        $.ajax({
            url: 'http://news.zing.vn/api/mobile/a' + articleId + '.json',
            dataType: 'json',
            success: function(json, textStatus, jqXHR) {
                var data = json.data[0],
                    html;

                var layout = 'article_layout';
                if(data.type=='picture' || data.type=='video') {
                    layout = 'pictures_layout';
                }

                //log(data);

                html = '<section class="article_content '+layout+' inline inactive">' +
                        /*
                        (articleList.length > 0 ?
                            '<div class="autoLoadNotice">' +
                                'Zing.vn tự động tải bài kế tiếp giúp bạn đọc dễ dàng hơn ' +
                                '<a href="#">Tắt chế độ tự động tải</a>' +
                            '</div>' : '') +
                        */
                        '<header>' +
                            '<p class="cate" itemprop="articleSection">' + data.catechild + ' </p>' +
                            '<time datetime="' + data.time + '">' + data.time + '</time>' +
                            '<h1 itemprop="name">' + data.title + '</h1>' +
                            '<div class="summary">' +
                            '<p itemprop="description">' + data.summary + '</p>' +
                            '</div>' +
                        '</header>' +
                        '<article><div class="content" itemprop="articleBody">' + data.content + '</div>';
                html += '<div id="credit">';
                if (data.author) {html += '<p class="author">'+data.author+'</p>';}
                if (data.credit) {html += '<p class="credit">'+data.credit+'</p>';}
                html += '</div>';
                html += '<div class="fb-like" data-href="http://news.zing.vn/zingnews-post'+articleId+'.html"></div>';
                html += '</article>';

                if (data.type!='picture' && data.relate && data.relate.length > 0) {
                    html += '<aside class="sidebar">' +
                            '<section class="related">' +
                            '<header>' +
                            '<h1>Liên quan</h1>' +
                            '</header>';
                    for (var i = 0, length = data.relate.length; i < length; i++) {
                        var relate = data.relate[i];

                        html += '<article>' +
                            '<header>' +
                            '<h1>' +
                            '<a href="' + relate.link + '">' + relate.title + '</a>' +
                            '</h1>' +
                            '</header>' +
                            '</article>';
                    }

                    html += '</section>';
                    html += '<div class="floating">' + $('.article_layout aside.sidebar div.floating').html() + '</div>';
                    html += '</aside>';
                }

                html += '</section>';

                var $section = $(html);
                $section.data({
                    title: data.title,
                    src: url
                });

                $section.attr('data-id', articleId);

                $section.find('.autoLoadNotice').on('click', function(e) {
                    e.preventDefault();

                    STOPPED = true;
                    $(window).off('scroll', onScroll);

                    $(this).fadeOut(function() {
                        $(this).remove();
                    });
                });

                $('.pTitle', $section).remove();
                $('.pHead', $section).remove();

                $elm.after($section);
                $elm.remove();

                var $content = $('article > .content', $section);
                article.formatContent($content);
                article.renderInnerVideo($content);
                article.renderInteractiveContent($content);
                article.renderTablePicture($content);
                article.renderComment($content);


                if (data.type!='video') {
                    //article.renderMetaBox($content);
                }


                $elements = $('.lazy_article');
                new FullscreenSlideshow().init($section);

                updateContentStack();
                page.socialplugin.updateSocialBox($section.find('.fb-like'));
                insertLazyElm();
                
                $('.wrapper > .sidebar').css({
                    'height':($('.wrapper > .sidebar').parents('.wrapper').height()-300)+'px'
                });
                
                //History.pushState({}, data.title, url);


            }
        });
    };

    var updateContentStack = function() {
        $contentStack = $('.article_content');
    };

    var isElementInViewport = function(index, el, offsetTop) {
        var $elem = $(el),
            viewport = {
                top: $window.scrollTop(),
                left: $window.scrollLeft()
            };

        offsetTop = offsetTop || 0;

        viewport.right = viewport.left + $window.width();
        viewport.bottom = viewport.top + $window.height();
        var bounds = $elem.offset();
        bounds.right = bounds.left + $elem.outerWidth();
        bounds.bottom = bounds.top + $elem.outerHeight();

        if (viewport.top >= bounds.top && el.tagName === 'SECTION') {
            currentArticleIndex = index;
        }

        return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top + offsetTop > bounds.bottom));
    };

    var insertLazyElm = function() {
        if (articleList.length > 0) {
            $elements = $('<div class="lazy_article" style="width:660px;float:left"></div>');
            $elements.data({
                src: articleList[0],
                id: getArticleId(articleList[0])
            });
            $discover.before($elements);
            articleList.shift();
            return $elements;
        }
    };

    var init = function(pArticle) {
        PAGEVIEW_TRACKED.push(window.location.href.split('#')[0]);

        article = pArticle;
        $window = $(window);
        $discover = $('#discover');

        $(".article_content:eq(0)").data({
            src: window.location.href,
            title: document.title
        }).attr('data-id', getArticleId(window.location.href));



        var tracker = page.storage.load('history');
        if(tracker==null || tracker===false) {tracker = "";}

        // always auto load inner article
        if(page.article.getArticleType()=='text') {
            log('Auto load inner article');
            var $inner_article = $('article .content .inner-article');
            $inner_article.each(function(i,elm){
                var href = $('a', elm).attr('href').replace(/#.*/ig,'');
                var articleid = getArticleId(href);
                if (tracker.search(articleid)<0 && articleList.indexOf(href)<0) {
                    articleList.push(href);
                }
            });
        }
        

        // auto load related article if on tablet (but not older than 14 days)
        if(DEVICE.type=='tablet') {
            log('Auto load related articles');
            $relate_articles = $('.article_content .related article');
            var type_filter = page.article.getArticleType();
            $relate_articles.each(function(i, elm) {
                var href = $('header a', elm).attr('href').replace(/#.+/ig,'');
                var time = new Date($('time',elm).attr('datetime'));
                var age = Math.round((now() - time.getTime())/86400000);
                if (age>14) return;
                if (type_filter=='picture' && !$(elm).hasClass('picture')) {
                    return;
                }
                if (type_filter=='text' && $(elm).hasClass('picture')) {
                    return;
                }
                var articleid = getArticleId(href);
                if (tracker.search(articleid)<0 && articleList.indexOf(href)<0) {
                    articleList.push(href);
                }
            });
        }
        
        
        
        // auto load next articles only if come direct, from external source or on tablet
        if(DEVICE.type!='desktop' || document.referrer=='' || document.referrer.search('http://news.zing.vn')<0) {
            log('Auto load next articles');
            $next_articles = $('.article_content .next_read article');
            $next_articles.each(function(i, elm) {
                var href = $('header a', elm).attr('href').replace(/#.+/ig,'');
                var articleid = getArticleId(href);
                if (tracker.search(articleid)<0 && articleList.indexOf(href)<0) {
                    articleList.push(href);
                }

            });
        } 

        
        
        /*
        $nextarticles = $('.article_content .next_read');        
        $('.article_content > aside').css('height',$('.article_content > article').height()+'px').append($nextarticles);
        */

        if (articleList.length > 0) {
            var $firstElement = insertLazyElm();

            $window.scroll(onScroll);
            updateContentStack();

            var popped = false, initialURL = window.location.href;

            window.addEventListener('popstate', function(e) {

                var initialPop = !popped && window.location.href == initialURL;
                    popped = true;

                if (initialPop) {
                    log('Initial Pop on load');
                    return;
                }

                log('History back!');
                setTimeout(function(){
                    scrollToArticle(window.location.href);
                },0);

            });
        }
    };

    this.isElementInViewport = isElementInViewport;
    this.init = init;
}

/* Formatting Article Content */
function Article() {
    var articles = $('article'),
        self = this,
        fullscreenSlideshow = new FullscreenSlideshow(),
        cachedArticleFormat,
        isAllowComment,
        shortURL;

    this.commentEnabled = function(){
        if (isAllowComment) return isAllowComment;
        isAllowComment = ($('#comments').length > 0);
        return isAllowComment;
    };

    this.isPRArticle = function(){
        return $('.pr_article').length>0 || $('img[src*="bs.serving-sys.com"]').length>0;
    }

    this.init = function () {

        if(self.getArticleType()=='video') {
            Player.setupVideo();
        }

        if($('#credit .source').length==0 && ($('.pr_article').length==0)) {
            $('.article_content > header .summary').addClass('zing');
        }
        self.renderArticleContent();        
        self.renderSocialPlugins();

        $('#attachments a').on('click',function(e){
            e.preventDefault();
            window.open($(this).attr('href'), $(this).text(), "height=600,width=800");
        });
        $('#metainfo .source a').on('click',function(e){
            e.preventDefault();
            var origin_title;

            page.showDialog(
                'Thông tin trích dẫn',
                '<p>Bài được Zing.vn đăng lại từ nội dung gốc theo liên kết bên dưới.</p>' +
                '<div style="font-weight:bold; font-size:1.1em;border: 1px solid #ccc;padding: 10px;margin-bottom: 10px;">'+$(this).text()+'</div>'
            );
        });

        if ((DEVICE.browser === 'chrome' || DEVICE.browser === 'firefox' || DEVICE.browser === 'safari') && ($('.pr_article').length==0) && $('.article_content.article_layout,.article_content.pictures_layout').length>0 && $('#chuyende').length==0) {
            var $firstElement = $('.article_content');
            var $recommend = $('<section>',{'class':'recommendation'});
            var $samecate = $('#discover .same_cate');
            $recommend.html($samecate.html());
            $firstElement.after($recommend);
            //$recommend.find('a').attr('target','_blank');
            $samecate.hide();
            if(window.location.hash.search('embed')<0) {
                new InfiniteArticle().init(self);    
            }
            
        }

        return this;
    };

    this.getArticleType = function () {
        if (cachedArticleFormat != null) return cachedArticleFormat;
        if ($('body#video').length > 0) {cachedArticleFormat = 'video'; return 'video';}
        if ($('#chuyende').length > 0) {cachedArticleFormat = 'special';return 'special';}
        var $content = $('.article_content');
        if ($content.length > 0) {
            if ($content.eq(0).hasClass('pictures_layout')) cachedArticleFormat = 'picture';
            else if ($content.eq(0).hasClass('article_layout')) cachedArticleFormat =  'text';
            else if ($content.eq(0).hasClass('infographic_layout')) cachedArticleFormat =  'infographic';
            else if ($content.eq(0).hasClass('stream_layout')) cachedArticleFormat =  'stream';
            return cachedArticleFormat;
        }
        cachedArticleFormat = null;
        return cachedArticleFormat;
    };

    this.getArticleId = function (url) {
        if(url) {
            var matched = url.match(/post([0-9]+)\.html/i);
            if (matched != null && matched.length>1) {
                return matched[1];
            } else {
                return null;
            }
        }
        if (page.getPageType() == 'article') {
            return window.location.href.replace(window.location.hash, '').replace(/http.*-post|\.html#*/gi, '');
        }
        return null;
    };

    this.getShortLink = function () {
        if (shortURL) return shortURL;
        var articleId = self.getArticleId();
        if (articleId != null) {
            shortURL = 'http://news.zing.vn/zingnews-post' + articleId + '.html';
        } else {
            shortURL = window.location.href;
        }
        //console.log(shortURL);
        return shortURL;
    };

    // setup link for social
    this.renderSocialPlugins = function (url) {
        url =  url || window.location.href.replace(window.location.hash, '');

        var article = {
            title: $('#content > header h1').text(),
            url: url,
            summary: $('#content > header .summary p').html()
        };

        var $shareButtons = $('.share_buttons');
        $shareButtons.find('li a').off('click');
        $shareButtons.find('li a').on('click', function(e) {
            e.preventDefault();
            var $this = $(this),
                $parent = $this.parents('li'),
                url,
                newWindow;

            if ($parent.hasClass('btn_facebook')) {
                if (page.comment.FBAvailable) {
                    FB.ui({
                        method: 'feed',
                        link: article.url,
                        ref: 'InnerArticle'
                    });
                } else {
                    alert("Không truy cập được vào Facebook");
                }
            } else if ($parent.hasClass('btn_zingme')) {
                url = 'http://link.apps.zing.vn/share?u=' + encodeURIComponent(article.url) + '&t=' + encodeURIComponent(article.title) + '&desc=' + encodeURIComponent(article.summary);
                newWindow = window.open(url, "", 'width=500,height=300,scrollbars=no');
                if (window.focus) {
                    newWindow.focus();
                }
            } else if ($parent.hasClass('btn_google')) {
                url = 'https://plus.google.com/share?url=' + encodeURIComponent(article.url);
                newWindow = window.open(url, "", 'menubar=no,toolbar=no,resizable=yes,scrollbars=no,height=600,width=550');
                if (window.focus) {
                    newWindow.focus();
                }
            }
        });
    };

    // setup article links on the page, this include attach click tracking mechanism
    this.renderFacebookWidgets = function(url, reRender) {
        var likeBox = '<div class="fb-like" data-href="' + url + '" data-layout="box_count" data-action="like" data-show-faces="false" data-share="true"></div>';
        if (DEVICE.screen!='wide') {
            likeBox = '<div class="fb-like" data-href="' + url + '" data-width="120" locale="en_US" data-layout="button_count" data-show-faces="false" data-share="false"></div>';
        }

        var $btnSocial = $('#pushnotification .btnSocial');
        if ($btnSocial.length > 0) {
            $btnSocial.html(likeBox);
            if (reRender) {
                FB.XFBML.parse($btnSocial[0]);
            }
        }
    };

    this.renderTablePicture = function($cnt) {
        // reformat all table in content
        var $tables = $cnt.find('> table');
        for (var i = 0, j = $tables.length; i < j; i++) {
            var $table = $tables.eq(i);

            $table.attr('cellpadding', "0").attr('cellspacing', "0").removeAttr('height').removeAttr('width').removeAttr('align');
            // if the table has picture, auto reformat
            if ($table.find('img').length > 0) {
                $table.addClass('picture');
                $table.find('td').each(function () {
                    var $this = $(this);

                    if ($this.find('img').length != 0) {
                        $this.addClass('pic');
                    } else {
                        var text = $.trim($this.text());
                        if (text === "" || text === "Nhập mô tả cho ảnh") {
                            $this.remove();
                        } else {
                            $this.addClass('caption');
                        }
                    }
                });
                $table.find('br').remove();
            }
        };
    };

    this.renderInnerVideo = function($cnt) {
        $('.inner-video a', $cnt).on('click',function(e){
            var $this = $(this);
            e.stopPropagation();
            e.preventDefault();
            var videolink = $this.attr('href')+'#singleplayer';
            var $container = $this.parents('.inner-video');
            //console.log($container.attr('full_height'));
            if($container.attr('full_height')) {
                $container.css('height',$container.attr('full_height')+'px');
            }
            $container.html($('<iframe>',{'src':videolink}).css({'width':'100%', 'height':'100%'}));
        });
    };

    this.renderInteractiveContent = function($cnt) {
        $('.interactive-content a', $cnt).on('click',function(e){
            e.preventDefault();
            var $this = $(this),
                winWidth = parseInt($this.attr('viewW')),
                winHeight = parseInt($this.attr('viewH')),
                videowindow = window.open($this.attr('href'), "interactive", "width="+winWidth+", height= "+winHeight+", left=300, top=300, resizable=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no");
        });

        self.renderAudioContent($cnt);
        self.renderMapContent($cnt);
    };

    this.renderAudioContent = function($cnt) {
        var $audios = $('.audio',$cnt);
        for(var i=0; i<$audios.length;i++) {
            var $audio = $audios.eq(i);
            if($audio.find('> a[href*=".mp3"]').length==1) {
                $audio.after('<div class="audio"><iframe src="http://news.zing.vn/interactive/page-5.html#'+$audio.find('> a[href*=".mp3"]').attr('href').replace(/w\d+\//ig,'')+'" style="width:100%; height: 80px;" class="formatted" ></iframe><p class="caption">'+$audio.text()+'</p></div>');    
                $audio.remove();
            }
            
            
        }
    };

    this.renderMapContent = function($cnt) {
        var $addresses = $('.mapviewer',$cnt);
        for(var i=0;i<$addresses.length;i++) {
            var $address = $addresses.eq(i);
            if($address.find('> a[href*="google.com/maps/"]').length==1) {
                $address.after('<div class="mapviewer"><iframe src="http://news.zing.vn/interactive/page-6.html#'+$address.find('>a').attr('href')+'" class="formatted" style="width:100%; height:300px;"></iframe><p class="caption">'+$address.text()+'</p></div>');    
                $address.remove();
            }            
            
        }
    }

    this.renderInfographicContent = function($cnt) {
        var $infographics = $cnt.find('.picture img');
        var src;
        for (var i = 0, j = $infographics.length; i < j; i++) {
            var $zoomer = $infographics.eq(i);
            src = $zoomer.attr('src');
            $zoomer.after('<span class="zoom-instruct"></span>');

            //$(zoomer).attr('src',src.replace(/\/w\d+\//,'/w1024/'));
            $zoomer.attr('data-zoom-image',src.replace(/\/w\d+\//,'/'));

            $zoomer.ensureLoad(function() {
                var originWidth = $zoomer.width();
                var originHeight = $zoomer.height();

                log('Original Loaded | '+originWidth + ":" + originHeight);

                // if this is a vertical infographic that is long enough, don't do zoomer
                if (originHeight/originWidth > 1.5) {
                    $zoomer.siblings('.zoom-instruct').remove();
                    return;
                }
                var fullimg = $('<img>',{'src':src.replace(/\/w\d+\//,'/')}).ensureLoad(function(){
                    var fullWidth = $(fullimg).width();
                    var zoomtype = 'inner';
                    // if the zoom ratio is less than 2, don't magnify
                    if (fullWidth/originWidth < 2) {
                        $zoomer.siblings('.zoom-instruct').remove();
                        return;
                    }
                    loadPlugin('elevateZoom', 'elevateZoom.js', function(){
                        log('Initialize zoom');
                        $zoomer.siblings('.zoom-instruct').remove();
                        $zoomer.elevateZoom({
                            responsive: true,
                            loadingIcon:true,
                            zoomType:zoomtype,
                            lensSize:'300',
                            cursor:'move',
                            loadingIcon:'http://stc.v3.news.zing.vn/css/img/icon_loading_small.gif'
                        });

                    });
                });
                $('body').append($(fullimg).hide());
            });
        }
    };

    this.renderPhotoCompare = function($cnt) {
        if($cnt.find('.twentytwenty-container').length==0) return;
        (new PhotoCompare()).init();
    }

    this.renderComment = function($cnt) {
        var $parent = $cnt.parents('section.article_content');
        var $cmt = $('<div>');
        var articleid = $parent.attr('data-id');
        if(articleid==null) {articleid=self.getArticleId();}
        new Comment(articleid,$cmt);
        if($('#worldcup').length>0 && $('#livestream').length>0) {
            $('.rightcontent > *').remove();
            var $clock = $('<div>',{'id':'timer','class':'vn'}).html('<span class="clock"></span><span class="timezone"><a href="#" class="clockVN active">Việt Nam</a> | <a href="#" class="clockBr">Brazil</a></span>');
            $clock.find('a').on('click',function(e){
                e.preventDefault();
                $clock.find('a').removeClass('active');
                $(this).addClass('active');
                if($(this).hasClass('clockVN')) {
                    $clock.addClass('vn');
                } else {
                    $clock.removeClass('vn');
                }
            });
            $('.rightcontent').append($clock);
            setInterval(function(){
                var m = new Date(), minute,hour,sec;
                if($clock.hasClass('vn')) {                    
                    minute = (m.getMinutes()<10) ? '0'+m.getMinutes() : m.getMinutes();
                    hour = (m.getHours()<10) ? '0'+m.getHours() : m.getHours();
                    sec = (m.getSeconds()<10) ? '0'+m.getSeconds() : m.getSeconds();    
                } else {
                    minute = (m.getUTCMinutes()<10) ? '0'+m.getUTCMinutes() : m.getUTCMinutes();
                    hour = (m.getUTCHours()-3<10) ? '0'+(m.getUTCHours()-3) : m.getUTCHours()-3;
                    sec = (m.getUTCSeconds()<10) ? '0'+m.getUTCSeconds() : m.getUTCSeconds();  
                }
                
                $clock.find('.clock').html(hour+':'+minute+':'+sec);
            },1000);
            $('.rightcontent').append($cmt);
        } else {
            $parent.append($cmt);    
        }
        
    };

    this.renderMetaBox = function($cnt) {
        var $metabox = $cnt.parents('article').find('#metainfo');
        var articleid = $cnt.parents('.article_content').attr('data-id');
        if(articleid==null) {articleid=self.getArticleId();}
        var $rating;
        log('Setting up metabox for article#'+articleid);
        //log($cnt.parents('.article_content'));
        if($metabox.length>0) {
            $metabox.addClass('metabox').attr('id','');
            if($metabox.find('#articleRating').length > 0) {
                $rating = $('#articleRating');
            } else {
                $rating = $('<div>');
                $metabox.append($rating);
            }
            self.setupRating(articleid,$rating);
        } else {
            $metabox = $('<div>').addClass('metabox');
            $cnt.parents('article').append($metabox);
            $rating = $('<div>');
            self.setupRating(articleid,$rating);
            $metabox.append($rating);
        }
    };

    this.formatContent = function($cnt) {
        $cnt.find('*:not(".percent,.formatted")').removeClass("pBody").removeAttr("style");
        // auto wrap textNode and clear empty nodes
        var textNode = $cnt.contents().filter(function () {
            return this.nodeType == 3;
        });
        for (var a = 0, b = textNode.length; a < b; a++) {
            if ($(textNode[a]).text() == "" || $(textNode[a]).text() == "\n") $(textNode[a]).remove();
            else {
                $(textNode[a]).wrap('<p>');
            }
        };

        // remove unncessary tags
        $cnt.find('> p ~ br').remove();
        $cnt.find('p > br + br').after('<span class="linebreak"></span>').remove();
        $cnt.find('> p').filter(function () {
            return ($(this).find('img').length == 0) && ($(this).find('iframe').length == 0) && ($.trim($(this).text()) == "");
        }).remove();
        $cnt.find('> p').filter(function(){
            return ($(this).find('img').length>0 && $(this).text().trim()=='') ;
        }).addClass('inline-image');
        $cnt.find('> em').prev('p').css('display', 'inline');
    };

    /**
     * Format article content & setup tools
     */
    this.renderArticleContent = function () {
        var $content = $('article > .content');

        if ($content.length == 0) {
            return;
        }

        this.renderInnerVideo($content);
        this.renderInteractiveContent($content);
        this.renderTablePicture($content);
        this.renderPhotoCompare($content);

        // render toolbox (left side box) for article page
        if(!fullbackground) {
            var $pushNotification = $('#pushnotification');
            if ($pushNotification.length == 0) {

                $('body').append($('<div>', {
                    'id': 'pushnotification'
                }).html("<a href='javascript:page.scrollTo();' class='button btnToTop'>Đầu trang</a>"+'<div class="wrapper"></div>'));
                $('body').append("<a href='javascript:page.scrollTo();' class='button btnToTop'>Đầu trang</a>");

                $pushNotification = $('#pushnotification');

                $pushNotification.find('.wrapper').append($('<div>', {
                    'class': 'actions'
                }));

                $pushNotification.find('.wrapper .actions').html(
                    "<a href='http://news.zing.vn' class='button btnHome'>Trang chủ</a>" +
                    "<div id='font'><a href='#' class='btnRegularFont'>Abc</a><a class='btnSerifFont' href='#'>Abc</a></div>" +
                    "<div class='btnSocial'></div>"+
                    "<a href='javascript:page.article.reportError();' class='button btnError'>Báo lỗi bài viết</a>"
                );

                self.renderFacebookWidgets(self.getShortLink());

                if ($.cookie('font') == null) {
                    $pushNotification.find('.btnRegularFont').addClass('current');
                } else {
                    $pushNotification.find('.btnSerifFont').addClass('current');
                }
                $pushNotification.find('#font a').on('click', function () {
                    if ($(this).hasClass('btnSerifFont')) {
                        $.cookie('font', 1, {
                            expires: 100,
                            path: '/'
                        });
                        $('body').addClass('serif');
                        //ga('send', 'event', 'Article', 'Change Font', 'Serif');
                    } else {
                        $.removeCookie('font');
                        $('body').removeClass('serif');
                        //ga('send', 'event', 'Article', 'Change Font', 'Standard');
                    }
                    $pushNotification.find('#font a').removeClass('current');
                    $(this).addClass('current');
                    return false;
                });


            }
        }
        

        // automatically insert article link on copy of text
        $content.bind('copy', function () {
            page.insertCopy();
            //ga('send', 'event', 'Article', 'Copy Text', window.location.pathname);
        });

        // grammar report mechanism activate when user select text
        $content.bind('mouseup', function (e) {
            var selectedText = page.getSelection();
            if (selectedText != false && selectedText != '') {
                page.showBottomBar();
                var $btnError = $pushNotification.find('.btnError');
                if ($btnError.hasClass('active')) {
                    $btnError.removeClass('active');
                } else {
                    $btnError.addClass('active');
                }
            } else {
                $pushNotification.find('.btnError').removeClass('active');
            }
        });

        // format content
        if(page.article.getArticleType()!='special') {
            // clear all styles
            this.formatContent($content);
            /*
            $content.find('*:not(".percent,.formatted")').removeClass("pBody").removeAttr("style");
            // auto wrap textNode and clear empty nodes
            var textNode = $content.contents().filter(function () {
                return this.nodeType == 3;
            });
            for (var a = 0, b = textNode.length; a < b; a++) {
                if ($(textNode[a]).text() == "" || $(textNode[a]).text() == "\n") $(textNode[a]).remove();
                else {
                    $(textNode[a]).wrap('<p>');
                }
            };

            // remove unncessary tags
            $content.find('> p ~ br').remove();
            $content.find('p > br + br').after('<span class="linebreak"></span>').remove();
            $content.find('> p').filter(function () {
                return ($(this).find('img').length == 0) && ($(this).find('iframe').length == 0) && ($.trim($(this).text()) == "");
            }).remove();
            $content.find('> p').filter(function(){
                return ($(this).find('img').length>0 && $(this).text().trim()=='') ;
            }).addClass('inline-image');
            $content.find('> em').prev('p').css('display', 'inline');
            */
        }


        // Zooming/slideshow mechanism for image in article
        fullscreenSlideshow.init($('#content'));

        // setup infographic content
        if(page.article.getArticleType()=='infographic') {
            this.renderInfographicContent($content);
        }

        if(self.commentEnabled()) {
            this.renderComment($content);
        }

        self.renderMetaBox($content);
    };


    /**
     * Send user feedback on article content
     */
    this.reportError = function () {

        var selectedText = page.getSelection();
        if (selectedText == false || selectedText == null) {
            selectedText = "";
        }
        selectedText = $.trim(selectedText);

        var dialogMessage = '';
        if (selectedText.length > 0) {
            dialogMessage += '<p class="label">Nội dung chứa lỗi:</p>' +
                    '<blockquote class="error"><p>'+ selectedText +'</p></blockquote>' +
                    '<p class="label">Giải thích/sửa lỗi (không bắt buộc):</p>';
        } else {
            dialogMessage += '<p class="label">Nhập thông tin báo lỗi vào ô bên dưới</p>';
        }

        dialogMessage += '<div><textarea id="errorContent"></textarea></div>';

        page.showDialog(
            'Báo lỗi thông tin bài viết',
            dialogMessage, {
                submit: {
                    text: 'Gửi báo lỗi',
                    action: function () {
                        var errorContent = $.trim($('#errorContent').val());
                        if (errorContent.length > 0) {
                            var reportContent = '';
                            if (selectedText.length > 0) {
                                reportContent += "[Lỗi]\n" + selectedText + "\n";
                            }
                            reportContent += "[Sửa]\n" + errorContent;

                            $.ajax({
                                type: 'POST',
                                url: "http://news.zing.vn/input/grammarreport.aspx?id=" + page.article.getArticleId(),
                                cache: false,
                                data: {
                                    content: reportContent
                                }
                            }).done(function () {
                                //ga('send', 'event', 'Article', 'Report Error', window.location.pathname);
                                //console.log($.cookie('grammar'));
                                page.closeDialog();
                                page.showDialog(
                                    'Báo lỗi thông tin bài viết',
                                    '<p>Cám ơn bạn đã báo lỗi bài này. Zing News sẽ cố gắng sửa nhanh nhất lỗi bạn đã báo. Bạn sẽ có thể báo lỗi bài này lại sau 24 tiếng.</p>'
                                );
                            });
                        } else {
                            page.closeDialog();
                            page.showDialog(
                                'Thông báo',
                                '<p>Để báo lỗi, bạn cần nhập nội dung có lỗi trong bài, hoặc chú thích thông tin bị sai của bài viết.</p>'
                            );
                        }

                    }
                }
            }
        );
    };

    /**
     * Setup rating  article
     */
    this.setupRating = function(id, parent){
        if (id==null) return;
        log('Setup rating box for article '+id);
        var ratingList = page.storage.load('ratingList');
        var articleid = id;
        var $articleRating = $(parent);

        if (ratingList == null || ratingList === false) {
            //log('Rating list is empty');
            ratingList = "";
        }

        if (ratingList.search(articleid) >= 0) {
            log('Article is already rated!');
            $articleRating.remove();
            return;
        }


        $articleRating.addClass('ratingbox').attr('data-id',articleid).html(
            '<p class="heading">ĐÁNH GIÁ BÀI VIẾT</p>'
            +'<p>Giúp Zing.vn ngày càng nâng cao chất lượng nội dung bằng cách cho chúng tôi biết bạn đánh giá thế nào về bài viết này:</p>'
            +'<ul>'
            +'<li class="ratingGood"><strong>Rất tốt!</strong> Thông tin nhanh, nội dung trung thực và khách quan.</li>'
            +'<li class="ratingNormal"><strong>Bình thường:</strong> Thông tin hữu ích, nội dung không lỗi.</li>'
            +'<li class="ratingBad"><strong>Kém:</strong> Nội dung không có giá trị, nhiều lỗi</li>'
            +'</ul>'
        );


        $articleRating.find('li').on('click',function(){
            var feedback = 2,
                score = 0;
            if ($(this).hasClass('ratingGood')) {
                feedback = 1;
                score = 1;
            } else if ($(this).hasClass('ratingBad')) {
                feedback = 3;
                score = -1;
            }

            $.ajax({
                type: 'POST',
                cache: false,
                url: "http://news.zing.vn/input/rating.aspx?id=" + articleid + "&value=" + feedback
            }).success(function() {
                //ga('send', 'event', 'Article', 'Rating', window.location.pathname, score);
                // save the article id  so that we don't display message anymore
                ratingList += articleid+',';
                page.storage.insert('ratingList', ratingList);
                if (feedback == 3) {
                    $articleRating.html('<div class="result">Cám ơn bạn đã đánh giá. Ban biên tập đã được thông báo về ý kiến của bạn và sẽ cố gắng nâng cao chất lượng bài viết.</div>');
                } else {
                    $articleRating.html('<div class="result">Zing cám ơn bạn đã đánh giá và rất vui vì bài viết đã đem lại thông tin hữu ích cho bạn.<br /><a href="#share">Chia sẻ bài viết cho bạn bè</a></div>');
                    $articleRating.find('.result a').on('click', function(e){
                        e.preventDefault;
                        if (page.socialplugin.FBAvailable) {
                            FB.ui({
                                method: 'feed',
                                link: page.article.getShortLink(),
                                ref: 'InnerArticle'
                            });
                        } else {
                            alert("Không truy cập được vào Facebook");
                        }
                    });
                }

            }).fail(function(){

            });
        });

        $articleRating.show();
    };

    // fetch articles from api
    this.fetchArticle = function (dataURL, callback, maxage) {
        var cached = page.storage.loadContent(dataURL);
        var limit = (maxage) ? maxage : 30;
        if (cached !== false && cached != null && cached.age < limit) {
            try {
                if (callback && typeof callback == 'function') {
                    var new_articles = JSON.parse(cached.content.data);
                    callback(new_articles);
                }
                return;
            } catch (e) {}
        }
        $.ajax({
            url: dataURL,
            dataType: "json"
        }).done(function (result) {
            page.storage.insertContent(dataURL, JSON.stringify(result));
            if (callback && typeof callback == 'function') {
                //console.log(result.data);
                callback(result.data);
            }
        });
    };

    // render article HTML
    this.renderArticleHTML = function(a, tracker) {
        var $output = $('<article>').attr('data-source',a.link);
        var link = a.link;
        if(tracker) link += '#'+tracker;
        if (a.type=='video') {$output.addClass('video');$output.append('<p class="type">Video</p>');}
        else if (a.type=='hasvideo') {$output.addClass('hasvideo');$output.append('<p class="type">Video</p>');}
        else if (a.type=='picture') {$output.addClass('picture');$output.append('<p class="type">Ảnh</p>');}
        $output.append('<div class="cover" style="background-image: url('+a.cover+')"><a href="'+link+'"><img src="'+a.cover+'" style="display:none;" /></a></div>');
        $output.append('<header><h1><a href="'+link+'">'+a.title+'</a></h1><time datetime="">'+page.formatTime(parseInt(a.time))+'</time><p class="cate">'+a.cateparent+'</p><p class="summary">'+a.summary+'</p></header>');                
        return $output;     
    }

}

/* Facebook intergration */
function SocialPlugin() {
    var self = this;

    this.FBAvailable = false,this.isFBLogin = false;
    this.userinfo = null;


    // initialization, checking facebook connection,...
    this.init = function () {
        jQuery.ajax({
            async: true,
            type: 'GET',
            url: '//connect.facebook.net/vi_VN/all.js#xfbml=1&appId=622829237762080',
            dataType: 'script',
            cache: true,
            data: null,
            complete: function (xhr, status) {
                // setup social components
                if (xhr.status == 200) {
                    self.FBAvailable = true;
                    log('Facebook is accessible!');
                    window.fbAsyncInit = function () {
                        if (FB) {
                            FB.init({
                                appId: APP_ID,
                                logging: false,
                                status: true, // Check Facebook Login status
                                cookie: true
                            });

                            $('body').addClass('fbonline');

                            if (DEVICE.screen == 'wide' && page.getPageType() == 'article' && $('body').attr('id') != 'video' && $('#infographic').length < 0) {
                                log('Setup Recommendation Bar');
                                $('body').append('<div class="fb-recommendations-bar" data-trigger="50%" data-site="news.zing.vn" data-num-recommendations="3" data-max-age="1" data-read-time="10" data-side="right" data-action="recommend"></div>');
                            }

                            if (page.getPageType() == 'article') {
                                var $likeButtons = $('.article_content article .fb-like');
                                $likeButtons.each(function(index, elm){
                                    page.socialplugin.updateSocialBox(elm);
                                });
                            }

                            // show follow button on toolbox
                            if ($('#toolbox .toTop').length > 0) {
                                $('#toolbox .toTop').after('<li class="facebook"><a href="javascript:page.showFollowDialog();" title="Quan tâm trên Facebook"><span>Facebook</span></a></li>');
                            }

                            self.getUserInfo(function(user){
                                if(user==null) return;
                                $('.commentbox .content label').html(
                                    '<img src="'+user.avatar+'" width="40" height="40" class="avatar" />'
                                    +'<strong>'+user.name+'</strong> (<a href="javascript:page.socialplugin.logout();" title="Thoát">Thoát</a>)'
                                );
                                $('.commentbox .btnSubmit').after('<label class="sharefb"><input type="checkbox" value="1" checked>Chia sẻ Facebook</label>');
                            });

                            FB.Event.subscribe('edge.create', function(url,elm){
                                $(elm).parents('.btnSocial').css('overflow','visible');
                                self.showFanpagePopup();
                            });

                            self.renderEmbedPost();

                            FB.XFBML.parse();

                            
                        }
                    };
                }
                else {
                    log('Facebook is not accessible!');
                    $('#pushnotification .btnFacebook').hide();
                    $('.fb-like').hide();
                }

            }

        });

    };

    // a very simple way to generate identification for user
    this.generateUID = function(){
        var identifier = (new Date()).getTime();
        identifier = identifier.toString()+Math.round(Math.random()*10000);
        return 'user_'+identifier;
    };

    // open fanpage follow box
    this.showFanpagePopup = function(){
        if (FB==undefined) return;
        if (self.userinfo==null || self.isFBLogin===false) {
            var show_popup = page.storage.loadContent('popup_follow');
            // only show the first time or at least 7 days separated
            if(show_popup==null || show_popup===false || show_popup.age > 10000) {
                page.showFollowDialog();
                log("User hasn't login, but last popup is MORE than 7 days ago --> show");
            } else {
                log("User is not login, and last popup is LESS than 7 days ago --> no show");
            }
            return;
        }        
        FB.api({
            method: 'fql.query', 
            query:  'SELECT uid FROM page_fan WHERE uid='+self.userinfo.id+' AND page_id=1414411772114879'
        }, function(resp) {
            var show_popup = page.storage.loadContent('popup_follow');
            if (!resp || resp.error) {
                // error (no authorization)                
                if(show_popup==null || show_popup===false || show_popup.age > 10000) {
                    page.showFollowDialog();
                    log("Error authenticating user, but last popup is MORE than 7 days ago --> show");
                }  else {
                    log("Error authenticating user, but last popup is LESS than 7 days ago --> no show");
                }
            } else {
                if (resp.length) {
                    // already a fan, so no asking                
                    log("User is login and already be a fan --> no show");
                } else {
                    if(show_popup==null || show_popup===false || show_popup.age > 10000) {
                        log("User is login and hasn't liked yet, last popup is MORE than 7 days ago --> show");
                        page.showFollowDialog();                        
                    }  else {
                        log("User is login and hasn't liked yet, but last popup is LESS than 7 days ago --> no show");
                    }
                }
            }
            
        });
    }

    // login
    this.login = function(callback, facebook){
        log('Logging user in...');
        // if user already login
        if(self.userinfo) {
            if (callback && typeof callback == 'function') {
                callback(self.userinfo);
            }
        }

        // if facebook available, and we are not on mobile
        if((DEVICE.type=='desktop')&& (facebook==null || facebook!==false) && self.FBAvailable) {
            FB.login(function(response) {
                if (response.authResponse) {
                    log("Login with FB successful");
                    self.isFBLogin = true;
                    self.getUserInfo(function(user){
                        if(callback && typeof callback=='function') {
                            callback(user);
                        }
                    });
                } else {
                    log('User cancelled login or did not fully authorize.');
                    self.login(callback, false);
                }
            },{scope: 'publish_actions,publish_stream'});
            return;
        }

        // else ask user for info
        page.showDialog(
            'Thông tin người dùng',
            '<p>Để gửi bình luận, bạn vui lòng cung cấp thông tin:</p>'
            +'<form>'
            +'<p><label>Họ và tên</label> <input type="text" id="comment_name" maxlength="25"  /></p>'
            +'<p><label>Email</label> <input type="text" id="comment_email"  /></p>'
            +'</form>',
            {
                submit: {
                    text: 'Gửi bình luận',
                    action: function(){
                        var username = $('#comment_name').val().trim();
                        var useremail = $('#comment_email').val().trim();
                        if(username!='' && useremail!='') {
                            log('New user. Generate new user!',self.userinfo);
                            self.userinfo = {
                                id: self.generateUID(),
                                name: username,
                                email:useremail,
                                avatar:''
                            };

                            //page.storage.insert('userinfo',JSON.stringify(self.userinfo));

                            if(callback && typeof callback=='function') {
                                callback(self.userinfo);
                            }
                            page.closeDialog();
                        } else {
                            alert('Bạn cần phải cung cấp tên và email để gửi bình luận!');
                        }

                    }
                },
                cancel: {
                    text:'Đóng',
                    action: function(){
                        log('User provide no information!');
                        page.closeDialog();
                        setTimeout(function(){
                            page.showDialog(
                                'Bình luận chưa được gửi',
                                '<p>Bạn chưa đăng nhập hoặc chưa điền thông tin cá nhân. Để gửi bình luận, bạn cần phải cung cấp thông tin người dùng. Vui lòng thử lại.</p>'
                            );
                        },100);

                    }
                }
            }
        );
    };

    // Logout
    this.logout = function() {
         self.userinfo = null;
         page.storage.clear('userinfo');
          if (typeof FB == undefined) return;
          FB.logout(function(response){
              self.userinfo=null;
              page.showDialog(
                    'Thông báo',
                    '<p>Bạn đã đăng xuất thành công!</p>'
              );
              if(page.getPageType()=='article' && page.article.commentEnabled()) {
                  $('.commentbox label').html('Bình luận');
              }
          });
    };

    // Get user info
    this.getUserInfo = function(callback){
        log('Checking login status');

        // if already checked before
        if (self.userinfo!=null) {
            log('User already login!');
            if(callback && typeof callback=='function') {
                log(self.userinfo);
               callback(self.userinfo);
            }
            return;
        } else {
            log('User not login yet');
        }


        if (DEVICE.type!='desktop' || !self.FBAvailable) {
            log('On mobile or FB is not available, let user enter manually');
            if(callback && typeof callback=='function') callback();
            return;
        };


        // fb available, looking for fb info first
        // log('Checking Facebook login status');
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;
                $('body').addClass('fbAuthorized');

                FB.api('/'+uid, function(user) {
                    self.userinfo = {
                        name: user.name,
                        email: user.username+'@facebook.com',
                        id:user.id,
                        avatar:'http://graph.facebook.com/'+user.id+'/picture?type=square'
                    };
                    self.isFBLogin = true;
                    log('Login with Facebook as '+self.userinfo.name);
                    //page.storage.insert('userinfo',JSON.stringify(self.userinfo));
                    if (callback && typeof callback == 'function') {
                        callback(self.userinfo);
                    }

                });
            } else {
                if (callback && typeof callback == 'function') {
                    callback();
                }
            }

        });
    };

    // push comment on facebook
    this.comment = function(content, url, callback){
        log('Attempt share comment on facebook');
        if (typeof FB == undefined || !self.isFBLogin) {
            log('Facebook is not accessible. Share cancel!');
            return;
        }

        log('Sharing article '+url);

        /* using custom open graph action */
        FB.api('me/zing_news:comment', 'post', {
            article : url,
            message: content,
            'fb:explicitly_shared': true
        }, function(response) {
            log(response);
            if (response && !response.error) {
                log ('Comment posted on Facebook');
                if(callback && typeof callback == 'function') {
                    callback(true);
                }
            } else {
                if(callback && typeof callback == 'function') {
                    callback(false);
                }
                log ('Unable to submit comment to Facebook');
            }
        });
    };

    // share url on facebook
    this.share = function(url) {
        FB.ui({
            method : 'feed',
            link : url,
            display: 'popup'
        }, function(response) {
        });
    };

    // like an url on facebook
    this.like = function(url, callback, message) {

        if (typeof FB == undefined) {
            log('Facebook is not accessible. Like cancel!');
            if(callback) callback(false);
            return;
        }

        log('User like an article: '+url);

        if (!self.isFBLogin) {
            FB.login(function(response) {
                if (response.authResponse) {
                    log("Login with FB successful");
                    self.isFBLogin = true;
                    self.like(url,callback);

                } else {
                    log('User cancelled login or did not fully authorize.');
                    page.showDialog(
                        'Đăng nhập thất bại',
                        '<p>Bạn cần đăng nhập Facebook và cấp quyền để có thể thực hiện tác vụ này. Bạn muốn thử lại?</p>',
                        {
                            submit: {
                                text:'Thử lại',
                                action: function(){
                                    self.like(url,callback);
                                    page.closeDialog();
                                }
                            },
                            cancel: {
                                text:'Đóng',
                                action: function(){
                                    page.closeDialog();
                                    callback(false);
                                }
                            }
                        }
                    );

                }
            },{scope: 'publish_actions,publish_stream'});
            return;
        }

        /*
        if(message==null) {
            page.showDialog(
                'Nội dung chia sẻ',
                '<p>Chia sẻ cảm nghĩ của mình về bài viết:</p>'+
                '<textarea id="like_comment" style="margin-top:10px; padding:10px; width:100%; height: 100px;"></textarea>',
                {
                    submit: {
                        text:'Chia sẻ lên Facebook',
                        action: function(){
                            var like_message = $('#like_comment').val().trim();
                            self.like(url,callback,like_message);
                            page.closeDialog();
                        }
                    },
                    cancel: {
                        text:'Bỏ qua',
                        action: function(){
                            self.like(url,callback,false);
                            page.closeDialog();                            
                        }
                    }
                }
            );
            return;
        }
        */

        var msg = null, fbshare = true;
        if (message===false) {
            fbshare = false;
        } else if (message!="") {
            msg = message;
        }

        FB.api('me/og.likes', 'post', {
            object : url,
            message: msg,
            'fb:explicitly_shared': false
        }, function(response) {
            log(response);
            if ((response.error && response.error.code==3501) || response.id) {
                var actionid;
                if(response.id) actionid = response.id;
                else {
                    actionid = response.error.message.match(/\d+$/i)[0];
                }
                log('Like success: '+url);
                page.socialplugin.showFanpagePopup();
                //page.storage.insert(url,actionid);
                callback(true,actionid);
            } else {
                log('Like fail: '+url);
                callback(false);
            }

        });
    };

    this.updateSocialBox = function(elm) {
        if (typeof FB == undefined) return;
        var $box = $(elm);
        $box.removeClass('fb-like').addClass('socialbox');
        $.ajax({
            //url: 'http://news.zing.vn/api/mobile/a' + articleId + '.json',
            url: 'https://api.facebook.com/method/links.getStats?urls='+$box.attr('data-href')+'&format=json',
            dataType: 'json',
            success: function(json, textStatus, jqXHR) {
                if (json && json.length>0) {
                    $box.html(
                        '<a class="btnLike" href="#like" title="Thích bài viết này"><span>'+json[0].like_count+'</span> Thích bài viết</a>'
                        + '<a class="btnShare" href="#share" title="Chia sẻ bài viết"><span>'+(json[0].share_count+json[0].comment_count)+'</span> Chia sẻ</a>'
                    );
                    $box.find('.btnLike').on('click',function(e){
                        e.preventDefault();
                        var $like = $(this);
                        self.like($box.attr('data-href'),function(result,id){
                             if(result && result===true) {
                                $like.addClass('liked');
                                if(id) {
                                    $like.attr('like',id);
                                    $like.find('span').on('click', function(e){
                                        e.stopPropagation();
                                        e.preventDefault();
                                        log('Unlike article ' + $box.attr('data-href'));
                                        FB.api(id, 'delete', function(response) {
                                            $like.removeClass('liked').removeAttr('like');
                                            $like.find('span').off('click');
                                        });

                                    });
                                }
                             } else {
                                 page.showDialog(
                                     'Lỗi mạng',
                                     '<p>Có lỗi xảy ra khi thực hiện tác vụ bạn yêu cầu. Có thể mạng của bạn không vào được Facebook lúc này. Vui lòng thử lại.</p>'
                                 );

                             }

                        });
                    });
                    $box.find('.btnShare').on('click',function(e){
                        e.preventDefault();
                        self.share($box.attr('data-href'));

                    });
                }
            },
            fail: function(){}
        });
    };

    this.renderEmbedPost = function() {
        var $embeds = $('.fbembed');
        log($embeds);
        for(var i=0;i<$embeds.length;i++) {
            var $embed = $embeds.eq(i);
            if($embed.find('> a[href*="facebook.com"]').length==1) {
                var $embed_html = $('<div>',{'class':'fb-post','id':'fbembed-'+i}).attr('data-width',$embed.parents('.content').width());
                $embed_html.attr('data-href',$embed.find('>a').attr('href'));                
                $embed.after($embed_html); 
                setTimeout(function(){
                    $embed.remove();
                },1000)    
            }                    
        }

    }
}

/* Comment */
function Comment(id, parent) {
    var checktimer, self=this, articleid = id, liveupdate = false, comment_timer;
    var $comment = $(parent), $commentField, $notes, $btnSubmit,$commentList, $btnMore;


    // fetch approved comments from CMS
    this.fetchComment = function(callback,pagination,timeorder,parent) {
        if(articleid==null) return;
        var commentFeed = 'http://news.zing.vn/api/comment.aspx?action=get&id='+articleid;
        if(!parent) {
            if(pagination) commentFeed += ('&page='+pagination);
            if((timeorder && timeorder===true) || liveupdate) commentFeed += ('&sortByTime=1');    
        } else {
            commentFeed += ('&parent_comment_id='+parent);
        }
        
        log('Retrieve comments list: '+commentFeed);
        $.getJSON(commentFeed, function (data) {
            if(callback && (typeof callback == 'function')) {
                callback(data);
            }
        });
    };

    this.renderComment = function(comment, isChild) {
        var comment_html='', $output=$('<li>',{'id':comment.ID});
        var like = (comment.Like==0)?"":comment.Like, dislike = (comment.Dislike==0)?"":comment.Dislike;        
        comment_html += '<p class="meta">';
        if (comment.Avatar.trim()!='') {            
            comment_html += '<img src="'+comment.Avatar+'" width="30" height="30" class="avatar" />';
        } else {
            $output.addClass('noavatar');
        }
        comment_html += '<span class="author">'+comment.DisplayName+'</span> ';
        comment_html += '<span class="time">'+page.formatTime(comment.CreationDate,{'friendly':true})+'</span></p>';                
        comment_html += '<div class="comment-content"><p>'+comment.Comment.replace(/\\n/g,'</p><p>')+'</p></div>';
        comment_html += '<div class="comment-actions"><a class="btnLike" href="#like"><span>'+like+'</span> Thích</a>';
        comment_html += '<a class="btnDislike" href="#dislike"><span>'+dislike+'</span> Không thích</a>';        
        if (isChild==null || isChild===false) {
            comment_html += '<a class="btnReply" href="#reply">Trả lời</a></div>';
        }
        $output.html(comment_html);
        if ((isChild==null || isChild===false) && comment.ReplyCount>0) {            
            
            var $replies = $('<ul>',{'class':'replies'});
            for (var a = 0; a < comment.Replies.length; a++) {
                $replies.append(self.renderComment(comment.Replies[a],true));
            };            
            $output.append($replies);
            if(comment.ReplyCount>3) {
                var $more = $('<a>',{'href':'#','class':'btnMore'}).html('Xem thêm').on('click',function(e){
                    var cur = this;
                    e.preventDefault(); 
                    var parent_comment_id = $(this).parents('li').attr('id');
                    self.fetchComment(function(replies){
                        for (var i = 0; i < replies.length; i++) {
                            if ($('#'+replies[i].ID).length>0) continue;
                            $replies.append(self.renderComment(replies[i],true))
                        };
                        $(cur).remove();
                    },1,true,parent_comment_id);
                });
                $output.append($more);
            }
        }

        $output.find('.comment-actions a').off('click').on('click',function(e){
            e.preventDefault();
            var $cmt = $(this);
            var cmt_id = $cmt.parents('li').attr('id');
            var cmt_name = $cmt.parents('li').find('.author').html();                
            if($cmt.hasClass('btnReply')) {
                log('User Reply');                    
                if($cmt.parents('li').find('.reply').length == 0) {
                    var $replyForm = $('<div>',{'class':'reply'}).html('<textarea comment-parent="'+cmt_id+'"></textarea><a href="#" class="btnSubmit disabled">Gửi trả lời</a>');
                    $cmt.after($replyForm);
                    $replyForm.find('.btnSubmit').on('click',function(e){
                        e.preventDefault();
                        $replyForm.hide();
                        var $reply = $(this).parents('.reply').find('textarea');
                        log('Reply to comment: #'+$reply.attr('comment-parent') + ' with content: '+$reply.val());
                        self.submitComment($reply.val(),true,$reply.attr('comment-parent'),function(){
                            if(result===false) {
                                $replyForm.show();
                            }
                        });
                    });
                } else {
                    $cmt.parents('li').find('.reply').remove();
                }

                return;
            }
            // otherwise, click on like or dislike button
            if($cmt.parents('.comment-actions').hasClass('disabled')) {
                page.showDialog(
                    'Thông báo',
                    '<p>Bạn đã bình chọn cho bình luận này rồi. Bạn chỉ có thể bình chọn 1 lần cho mỗi bình luận.</p>'
                );
                return;
            }

            var article_id = $(this).parents('.commentbox').attr('id').replace('comment-','');
            var cmt_action = 'like';
            if($cmt.hasClass('btnDislike')) cmt_action = 'dislike';
            $.ajax({
                url:'http://news.zing.vn/input/comment.aspx?action='+cmt_action+'&id='+article_id,
                type:'POST',
                dataType:'text',
                data: {
                    commentid:cmt_id
                },
                success:function(data, status, jqXHR){
                    if(data=='') {
                        $cmt.parents('.comment-actions').addClass('disabled');
                        $cmt.addClass('active');
                        var count = $cmt.find('span').text();
                        if(count=='') count=0;
                        $cmt.find('span').text(parseInt(count)+1);
                    } else {
                        log('Action Error');
                    }
                },
                fail: function(){
                    log('Error like action for comment #'+cmt_id);
                }
            });
        });
        
        return $output;
    }

    // update comments list
    this.updateComment = function(commentpage, orderbytime, pushed){
        var pagination = (commentpage==null)?1:commentpage;
        var comment, comment_content='';
        if(pushed && pushed===true) {
            log('Update comment live');
        }
        self.fetchComment(function(data){
            var total_page = Math.floor(parseInt(data.total_comment)/20)+1;
            if (data.comments.length>0 && commentpage==1 && $comment.find('.order').length==0 && !pushed) {
                $commentList.before('<div class="order"><label>Xếp theo: </label><a href="#" class="orderbyimportance current">Hay nhất</a> <a href="#" class="orderbytime">Mới nhất</a></div>');                                
                $comment.find('.order a').on('click',function(e){
                    e.preventDefault();
                    if($(this).hasClass('current')) return;
                    $(this).siblings('.current').removeClass('current');
                    $(this).addClass('current');
                    if($(this).hasClass('orderbyimportance')) {
                        $comment.removeAttr('orderbytime');
                    } else {
                        $comment.attr('orderbytime',1);
                    }
                    $commentList.html('');
                    var orderbytime = ($comment.attr('orderbytime')==1);
                    self.updateComment(1,orderbytime);
                });
            }
            for(var i=0,j=data.comments.length; i<j; i++){
                if(pushed && pushed===true) {
                    
                    if($('#'+data.comments[i].ID).length==0) {
                        //log('new comment: #'+data.comments[i].ID);
                        var $newcomment = self.renderComment(data.comments[i]);
                        $newcomment.css('top','-100px');
                        $commentList.prepend($newcomment);
                        $newcomment.transition({
                            'top': '0px'
                        }, 800);
                    } else {
                        //log('no new comment');
                    }
                    
                } else {
                    $commentList.append(self.renderComment(data.comments[i]));    
                }
                
            };
            $commentList.show();

            if(parseInt(data.current_page)<total_page) {
                $btnMore.attr('nextpage',(data.current_page+1)).show();
            } else {
                $btnMore.hide();
            }

        },pagination,orderbytime);
    };

    // check comment content
    this.checkCommentContent = function(comment,callback){

        // first check if comment is not empty
        if (comment.trim()=='') {
            page.showDialog(
                'Bình luận không có nội dung',
                '<p>Bình luận không thể để trống. Vui lòng chia sẻ vài dòng suy nghĩ của bạn về bài viết.</p>'
            );
            return;
        };

        // if comment is live, then don't check for comment length
        if(liveupdate) {
            if (callback && typeof callback == 'function') {
                callback();
            }
            return;
        }

        // check if comment is too short
        var words = comment.split(' ');
        if(words.length < 10) {
           page.showDialog(
                'Bình luận quá ngắn',
                '<p style="margin-bottom:8px;"><strong>Bình luận của bạn quá ngắn!</strong> Ban quản trị sẽ chỉ duyệt nếu bình luận dài tối thiểu 10 chữ. Bạn có muốn tiếp tục?</p><p style="font-size:0.9em;color:#888;">Chú ý: Bạn vẫn có thể gửi bình luận nhưng bình luận của bạn sẽ không vào danh sách chờ duyệt và sẽ không hiển thị.</p>',
                {
                    submit: {
                        text:'Quay lại cập nhật',
                        action:function() {
                            page.closeDialog();
                        }
                    },
                    cancel: {
                        text: 'Gửi bình luận',
                        action: function(){
                            page.closeDialog();
                            if (callback && typeof callback == 'function') {
                                callback();
                            }
                        }
                    }
                }
            );
            return;
        }
        // check if comment is Vietnamese
        if(!isVietnamese(comment)) {
            page.showDialog(
                'Bình luận bằng tiếng Việt có dấu',
                '<p><strong>Zing.vn chỉ đăng bình luận bằng tiếng Việt có dấu!</strong> Nội dung bình luận của bạn không có ký tự tiếng Việt. Bạn có muốn tiếp tục?</p>',
                {
                    submit: {
                        text:'Quay lại cập nhật',
                        action:function() {
                            page.closeDialog();
                        }
                    },
                    cancel: {
                        text: 'Gửi bình luận không dấu',
                        action: function(){
                            page.closeDialog();
                            if (callback && typeof callback == 'function') {
                                callback();
                            }
                        }
                    }
                }
            );
            return;
        }

        if (callback && typeof callback == 'function') {
            callback();
        }
    };

    // submit comment
    this.submitComment = function(comment_content,checked,parentid,callback){

        if (checked == null || checked===true) {
            log('Checking comment content');
            self.checkCommentContent(comment_content, function(){
                self.submitComment(comment_content,false,parentid);
            });
            return;
        }
        
        page.socialplugin.getUserInfo(function(user){            
            if(user==null) {
                log('User not login yet, asking for login ')
                page.socialplugin.login(function(info){
                    self.pushComment(
                        {
                            'userid': info.id,
                            'username':info.name,
                            'useremail':info.email,
                            'useravatar':info.avatar,
                            'comment_content':comment_content
                        }, function(result){
                            if(callback && typeof callback == 'function') {
                                callback(result);
                            }
                        },parentid
                    );
                });
            }
            else {
                log('User login! Now push comment');
                self.pushComment(
                    {
                        'userid': user.id,
                        'username':user.name,
                        'useremail':user.email,
                        'useravatar':user.avatar,
                        'comment_content':comment_content
                    }, function(result){
                        if(callback && typeof callback == 'function') {
                            callback(result);
                        }
                    }, parentid
                );
            }
        });
    };

    // push comment to CMS
    this.pushComment = function(comment, callback, replyto) {

        if(liveupdate) {
            //$comment.find('.form').css('opacity','0.5');
            $comment.find('.form').append('<div class="overlay"></div>');
        } else {
            $comment.find('.form').hide();    
        }
        

        // first fix comment content
        var commentContent = fixContent(comment.comment_content);
        commentContent = fixCommonErrors(commentContent);
        commentContent = capitalizeSentence(commentContent);

        var commentData = {
            'userid':comment.userid,
            'displayname' : comment.username,
            'email' : comment.useremail,
            'comment' : commentContent,
            'avatar':comment.useravatar
        };

        if(replyto) {
            commentData.parentid = replyto;
        }

        // then send comment to server
        $.ajax({
            type : 'POST',
            url : 'http://news.zing.vn/input/comment.aspx?action=post&id='+articleid,
            cache : false,
            data : commentData
        }).fail(function(jqXHR, status, error) {
            log("Network error: "+status);
            if(liveupdate) {
                $comment.find('.form .overlay').remove();
            } else {
                $comment.find('.form').show();    
            }
            
            page.showDialog(
                'Thông báo',
                '<p>Có lỗi xảy ra khi gửi bình luận của bạn. Bạn có thể thử lại sau vài phút.</p>'
            );
            if (callback && typeof callback == 'function') {
                callback(false);
            }
        }).done(function(data,status,jqXHR){
            // push comment to cms fail
            if (data.error==1) {
                log('Comment post to CMS fail');
                if(liveupdate) {
                    //$comment.find('.form').css('opacity','1');
                    $comment.find('.form .overlay').remove();
                } else {
                    $comment.find('.form').show();    
                }
                
                page.showDialog(
                    'Thông báo',
                    '<p>Có lỗi xảy ra khi gửi bình luận của bạn. Bạn có thể thử lại sau vài phút.</p>'
                );
                if (callback && typeof callback == 'function') {
                    callback(false);
                }
            }
            // push comment to cms succeed
            else {
                log('Comment post to CMS successfully');
                if(typeof cate_path != 'undefined') {
                    ga('send','event','Article','Comment',cate_path,commentContent.length);
                }
                // if already login to fb, attempt to share
                if(page.socialplugin.isFBLogin && replyto==null && !liveupdate) {
                    log('Prepare to share on Facebook...');
                    var $share = $comment.find('.sharefb input');
                    if ($share.length==0) {
                        log('Ask user if he want to share?');
                        page.showDialog(
                            'Chia sẻ bình luận',
                            '<p>Bình luận của bạn đã được gửi thành công! Bạn có muốn chia sẻ suy nghĩ của bạn về bài viết này trên Facebook cùng bạn bè?</p>',
                            {
                                submit: {
                                    text: 'Chia sẻ Facebook',
                                    action: function(){
                                        page.closeDialog();
                                        page.socialplugin.comment(comment.comment_content,$comment.attr('url'));
                                        page.socialplugin.showFanpagePopup();
                                    }
                                },
                                cancel: {
                                    text:'Bỏ qua',
                                    action:function(){
                                        page.closeDialog();
                                        page.socialplugin.showFanpagePopup();
                                    }
                                }
                            }
                        );
                    } else {
                        if($share.is(':checked')) {
                            log('User choose to share!');
                            page.socialplugin.comment(comment.comment_content,$comment.attr('url'));
                        } else {
                            log('User chose not to share comment. Cancel!');
                        }
                        page.showDialog(
                            'Bình luận đã được gửi',
                            '<p>Bình luận của bạn đã được gửi thành công và đang chờ duyệt trước khi hiển thị trên trang.</p>',
                            {
                                cancel: {
                                    text:'Đồng ý', 
                                    action: function(){
                                        page.closeDialog();
                                        page.socialplugin.showFanpagePopup();
                                    }
                                }
                            }
                        );
                    }
                } else {
                    
                    if(liveupdate) {
                        $comment.find('.form .overlay').append('<span>Bình luận của bạn đã được gửi và sẽ xuất hiện trong vài phút.</span>');
                        
                        setTimeout(function(){
                            //$comment.find('.form').css('opacity','1');
                            $comment.find('.form textarea').val('');
                            $comment.find('.form .overlay').fadeOut(500, function(){$(this).remove();});
                        },1000);
                        
                    } else {
                        page.showDialog(
                            'Bình luận đã được gửi',
                            '<p>Bình luận của bạn đã được gửi thành công và đang chờ duyệt trước khi hiển thị trên trang.</p>'
                        );
                    }
                }

                if (callback && typeof callback == 'function') {
                    callback(true);
                }
            }

        });
    };

    // setup comment box
    var init = function(){
        liveupdate = ($('#worldcup').length>0) && ($('#livestream').length>0) && ($('#livestream .controller').length>0);        
        log('Setting up comment for article#'+articleid);
        //setup
        $comment.attr('id','comment-'+articleid).addClass('commentbox').attr('url','http://news.zing.vn/zing-post'+articleid+'.html').html('');
        if (liveupdate) {
            $comment.html('<header><h1>Bình luận (tự động cập nhật)</h1></header>');
        } else {
            $comment.html('<header><h1>Bình luận</h1></header>');    
        }
        
        $comment.append(
            '<div class="form">'
            +'<p class="content"><label>Nội dung</label>'
            +'<textarea></textarea></p>'
            +'<p class="note"><span class="length">tối thiểu 10 chữ</span> <span class="vietnamese">tiếng Việt có dấu</span> <span class="link">không chứa liên kết</span> </p>'
            +'<a href="#" class="btnSubmit disabled">Gửi bình luận</a>'
            +'</div>'            
            +'<ul class="comments"></ul>'
            +'<a href="#" nextpage="1" style="display:none;" class="btnMore">Xem thêm</a>'
        );
        if(DEVICE.platform=='android') {
            $comment.find('textarea').before('<a target="_blank" href="market://details?id=com.vng.inputmethod.labankey" class="btnLabanKey">Cài LabanKey gõ tiếng Việt nhanh hơn</a>')
        }

        $commentField = $comment.find('.form textarea');
        $notes = $comment.find('.note span');
        $btnSubmit = $comment.find('a.btnSubmit');
        $commentList = $comment.find('ul.comments');
        $btnMore = $comment.find('> .btnMore');

        // setup submitting event
        $btnSubmit.on('click',function(e){
            e.preventDefault();
            self.submitComment($commentField.val(),true);
        });

        // user click to see more comments
        $btnMore.on('click',function(e){
            e.preventDefault();
            var orderbytime = ($comment.attr('orderbytime')==1);
            self.updateComment(parseInt($(this).attr('nextpage')),orderbytime);     
        });

        // setup event tracking on textarea
        $commentField.on('input propertychange',function(){
            clearTimeout(checktimer);
            checktimer = setTimeout(function(){
                var comment_content = $commentField.val();
                log('Checking comment content');
                if(comment_content.trim()==''){
                    $notes.removeClass('ok').removeClass('fail');
                    $btnSubmit.addClass('disabled');
                    return;
                }
                var words = comment_content.split(' ');
                if(words.length < 10) {
                    $comment.find('.length').addClass('fail').removeClass('ok');
                } else {
                    $comment.find('.length').addClass('ok').removeClass('fail');
                    $btnSubmit.removeClass('disabled');
                }

                if (words.length > 1) {
                    if(!isVietnamese(comment_content)){
                        $comment.find('.vietnamese').addClass('fail').removeClass('ok');
                    } else {
                        $comment.find('.vietnamese').addClass('ok').removeClass('fail');
                    }

                    if(comment_content.match(/https*:|www\.\S+/i)!=null) {
                        $comment.find('.link').addClass('fail').removeClass('ok');
                    } else {
                        $comment.find('.link').addClass('ok').removeClass('fail');
                    }
                }

            },200);
        });

        // update user info
        page.socialplugin.getUserInfo(function(user){
            if(user==null) return;
            $comment.find('.content label').html(
                '<img src="'+user.avatar+'" width="40" height="40" class="avatar" />'
                +'<strong>'+user.name+'</strong> (<a href="javascript:page.socialplugin.logout();" title="Thoát">Thoát</a>)'
            );
            if($comment.find('.sharefb').length==0) {
                $btnSubmit.after('<label class="sharefb"><input type="checkbox" value="1" checked>Chia sẻ Facebook</label>');
            }

        });

        // update comment list
        var orderbytime = ($comment.attr('orderbytime')==1);
        self.updateComment(1,orderbytime);        

        $comment.show();

        if(liveupdate) {
            log('Updating comment live!')
            $comment.addClass('liveupdate');
            $comment.find('.form').append('<img src="http://stc.v3.news.zing.vn/css/img/icon_loading_small.gif" width="16" height="16" class="loading" />' );
            comment_timer = setInterval(function(){
                self.updateComment(1,1,true);
            }, 10000);
        };

        

    };

    init();
}

/* Video Plugin */
function VideoPlayer() {
    var self = this,
        frameWidth = $('#video .player').width(),
        maxHeight = Math.round($(document).height()*0.6),
        playerHeight = Math.round(frameWidth*9/16),
        coverAnimations,
        IS_SINGLE_PLAYER = ($('#video.singleplayer').length > 0);

    if (IS_SINGLE_PLAYER) {
        playerHeight = $(document).height();
    } else if (playerHeight > maxHeight) {
        playerHeight = maxHeight;
        log('Exceed max height');
    }


    this.init = function(){

        // Setup preview video link
        if (window.location.hash.indexOf('next_video') >= 0) {
            $('#video_detail .player').append('<a href="javascript:Player.goBack();" class="btnPrev">Trước</a>');
        }

        // Setup next video link
        var $nextVideo = $('#video_detail .btnNext');
        if ($nextVideo.length > 0) {
            $nextVideo.attr('href', $nextVideo.attr('href') + '#next_video');
        };

        // calculate video duration
        var $timedurations = $('article.video .duration');
        var secs;
        for (var i = 0, j = $timedurations.length; i < j; i++) {
            secs = parseInt($timedurations.eq(i).text());
            if (secs>0) {
                var hr = Math.floor(secs / 3600);
                var min = Math.floor((secs - (hr * 3600))/60);
                var sec = secs - (hr * 3600) - (min * 60);

                if (hr==0) hr = ""; else hr += ":";
                if (min==0) min = ""; else min += ":";
                $timedurations.eq(i).text( hr + min + sec);
            }
        };

        

        return self;
    };

    this.goBack = function(){
        if (document.referrer!="") {
            window.location.href = document.referrer;
        } else {
            history.go(-1);

            setTimeout(function(){
                self.goBack();
            },500);
        }
    };

    this.setupVideo = function() {
        //log('Setting up video page');
        var videoUrl = null;
        var $videos = [],$video;

        // get the video URL
        var $player = $('#video_detail .player > iframe');

        if($player.length>0 && ($player.attr('src')!=null)) {
            if($player.attr('src').search('youtube.com')>=0 && $('.pr_article').length==0) {
                var v = 'http:'+$player.attr('src').replace(/\?.*/ig,'');
                var embed_url = 'http://tv.zing.vn/cms-embed?url='+v+'&cp_id=1327&key='+k('ztv@ZTV_123@z1327'+v)+'&autoplay=true&embed_type=cms&default_format=f720';
                log("Embed URL: " + embed_url);
                $player.attr('src',embed_url);
            }
            $player.css({'width':'100%','height':playerHeight+'px','display':'block'}).show();
            return;
        }


        $videos = $('#content .content iframe[src*="youtube.com"],#content .content iframe[src*="tv.zing.vn"],#content .content iframe[src*="mp3.zing.vn"]');
        if ($videos.length > 0) {
            $video = $videos.eq(0);
            videoUrl = $video.attr('src');
        }

        if (videoUrl == null) {
            return;
        }

        if (videoUrl.indexOf('tv.zing.vn') >= 0 || videoUrl.indexOf('mp3.zing.vn') >= 0) {

            var videoid = videoUrl.match(/\/([^.^/]*)(\.html)*$/i)[1];
            if (videoUrl.indexOf('autostart=false') > -1) {
                videoUrl = videoUrl.replace('autostart=false', 'autostart=true');
            } else {
                videoUrl += ((videoUrl.indexOf('?') === -1) ? '?' : '&') + 'autostart=true';
            }
            if ($player.length > 0) {
                $player.attr('src',videoUrl).css({'width':'100%','height':playerHeight+'px','display':'block'});
            } else {
                $('#video_detail .player').append($video);
                $video.attr('src', videoUrl);
                $video.css({'height':(playerHeight)+'px'} ).show();

            }
        } else if (videoUrl.indexOf('youtube.com') >= 0) {
            videoUrl = videoUrl.replace(/\?.*/g,''); // clear all parameters
            videoUrl += '?autoplay=1'; // set autoplay
            if (!IS_SINGLE_PLAYER) videoUrl += '&vq=hd720'; // if not embed mode, then select 720 quality

            if (DEVICE.type == "desktop") {
                $('#video_detail .player').append('<video id="youtubeplayer" width="'+frameWidth+'" height="'+playerHeight+'"><source src="'+videoUrl+'" type="video/youtube" ></video>').show();
                $('#youtubeplayer').mediaelementplayer({
                    iPhoneUseNativeControls: true,
                    AndroidUseNativeControls: true,
                    plugins: ['flash','silverlight'],
                    success: function(mediaElement, domObject) {
                        log('Done setting up player, now play');
                        mediaElement.addEventListener('canplay', function() {
                            mediaElement.play(); // Player is ready
                        }, false);

                    }

                });
            } else {
                $('#video_detail .player').append($video);
                $video.attr('src',videoUrl);
                $video.css({'height':(playerHeight)+'px'} ).show();
            }

           /*
            $('#video_detail .player').append($video);
            $video.attr('src',videoUrl);
            $video.css({'height':(playerHeight)+'px'} ).show();
            */
        }

        return false;
    };
}